1. はじめに
このセクションは規定ではありません。
グラフィックス処理ユニット(GPU)は、パーソナルコンピュータにおいて豊かなレンダリングや計算アプリケーションを可能にする重要な役割を担っています。 WebGPUは、Web上でGPUハードウェアの機能を公開するAPIです。 このAPIは、(2014年以降の)ネイティブGPU APIに効率良くマッピングできるよう、ゼロから設計されています。 WebGPUはWebGLとは関係なく、OpenGL ESを明示的にターゲットとしていません。
WebGPUは物理的なGPUハードウェアをGPUAdapterとして扱います。
アダプターへの接続は
GPUDeviceを介し、リソースの管理やデバイスのGPUQueueによるコマンド実行を行います。
GPUDeviceは、処理ユニットへ高速アクセス可能な独自メモリを持つ場合があります。
GPUBufferや
GPUTextureは、GPUメモリに裏付けられた物理リソースです。
GPUCommandBufferや
GPURenderBundleは、ユーザーが記録したコマンドのコンテナです。
GPUShaderModuleはシェーダーコードを格納します。他のリソース、例えばGPUSamplerや
GPUBindGroupは、GPUが
物理リソースを利用する方法を構成します。
GPUはGPUCommandBufferでエンコードされたコマンドを実行し、データをパイプライン(固定機能とプログラム可能ステージの混在)へ流します。プログラム可能ステージは
シェーダー(GPU上で動作する専用プログラム)を実行します。
パイプラインのほとんどの状態は
GPURenderPipelineや
GPUComputePipelineオブジェクトで定義されます。それ以外の状態は、コマンド
beginRenderPass()や
setBlendConstant()などでエンコード時に設定されます。
2. 悪意ある利用への考慮事項
このセクションは規定ではありません。 このAPIをWebで公開することによるリスクについて説明します。
2.1. セキュリティの考慮事項
WebGPUのセキュリティ要件はWebの従来通りであり、変更できません。 一般的なアプローチは、すべてのコマンドをGPUに到達する前に厳格に検証し、ページが自身のデータだけ操作できるようにすることです。
2.1.1. CPUベースの未定義動作
WebGPU実装は、ユーザーによるワークロードをターゲットプラットフォーム固有のAPIコマンドに変換します。ネイティブAPIはコマンドの正しい使用方法を規定しており(例:vkCreateDescriptorSetLayout)、有効な利用規則を守らない場合の結果は保証されません。 これは「未定義動作」と呼ばれ、攻撃者が自身の所有しないメモリにアクセスしたり、ドライバに任意のコードを実行させたりすることに悪用される可能性があります。
安全でない利用を禁止するため、WebGPUの許容動作範囲は全ての入力に対して定義されています。
実装はユーザーからの全ての入力を検証し、有効なワークロードのみドライバへ到達させる必要があります。本書では全てのエラー条件とその取り扱いについて規定しています。
例えば、copyBufferToBuffer()の「source」と「destination」の両方で、交差する範囲の同一バッファを指定すると、
GPUCommandEncoderはエラーを生成し、他の操作は行われません。
エラー処理の詳細は§ 22 エラーとデバッグを参照してください。
2.1.2. GPUベースの未定義動作
WebGPUのシェーダーはGPUハードウェア内部の計算ユニットで実行されます。ネイティブAPIでは、一部のシェーダー命令がGPU上で未定義動作となる場合があります。
これに対応するため、WebGPUではシェーダー命令セットとその動作を厳密に定義しています。シェーダーがcreateShaderModule()に渡される際、
WebGPU実装はプラットフォーム固有シェーダーへの変換や最適化を行う前に、必ず検証を行います。
2.1.3. 未初期化データ
一般に、新しいメモリの割り当ては、システム上で他のアプリケーションが残したデータが露出する可能性があります。 これに対処するため、WebGPUは概念的にすべてのリソースをゼロ初期化しますが、実際には開発者が手動で内容を初期化する場合はこの手順を省略することもあります。 シェーダー内の変数や共有ワークグループメモリもこれに含まれます。
ワークグループメモリのクリア方法はプラットフォームにより異なります。 ネイティブAPIがクリア機能を提供しない場合、WebGPU実装は計算シェーダー内で全呼び出しを使ってクリアを行い、同期後に開発者のコード実行を続行します。
GPULoadOp
"load"を"clear"へ変更)が必要になる場合があります。
そのため、すべての実装は、このパフォーマンス低下の可能性について開発者コンソールで警告を推奨すべきですが、実際に低下がなくても警告を表示すべきです。
2.1.4. シェーダー内の範囲外アクセス
シェーダーは物理リソースへ直接(例:"uniform"
GPUBufferBinding)、またはテクスチャユニット(座標変換を扱う固定機能ハードウェアブロック)経由でアクセスできます。
WebGPU APIの検証では、シェーダーへの全入力が提供され、使用法・型が正しいことのみ保証できます。
テクスチャユニットが関与しない場合、データへのアクセスが範囲内であることはAPIレベルでは保証できません。
シェーダーがアプリケーション所有外のGPUメモリへアクセスするのを防ぐため、WebGPU実装はドライバの「堅牢なバッファアクセス」モードを有効化し、アクセスをバッファ範囲内に制限する場合があります。
または、手動で範囲外チェックを挿入するようにシェーダーコードを変換することもできます。この場合、範囲外チェックは配列インデックスへのアクセスにのみ適用されます。構造体の単純なフィールドアクセスについては、ホスト側のminBindingSize検証により不要です。
シェーダーが物理リソース範囲外のデータを読み込もうとした場合、実装は以下のいずれかを許容します:
-
リソース範囲内の他の場所の値を返す
-
値ベクトル "(0, 0, 0, X)"(Xは任意)を返す
-
描画またはディスパッチ呼び出しを部分的に破棄する
シェーダーが物理リソース範囲外へデータを書き込もうとした場合、実装は以下のいずれかを許容します:
-
リソース範囲内の他の場所へ値を書き込む
-
書き込み操作を破棄する
-
描画またはディスパッチ呼び出しを部分的に破棄する
2.1.5. 無効なデータ
CPUからGPUへ浮動小数点データをアップロードする場合や、GPU上で生成する場合、無限大やNaN(非数)など、正しい数値に対応しない2進表現になる場合があります。このときのGPUの動作は、IEEE-754標準に準拠したGPUハードウェア実装の精度に依存します。 WebGPUは、無効な浮動小数点数値の導入が算術計算結果のみに影響し、それ以外の副作用は生じないことを保証します。
2.1.6. ドライバのバグ
GPUドライバも他のソフトウェア同様、バグの影響を受けます。バグが発生した場合、攻撃者がドライバの誤動作を利用して特権外のデータへアクセスする可能性があります。 このリスク低減のため、WebGPUワーキンググループは、WebGL同様にWebGPU適合テストスイート(CTS)をGPUベンダーのドライバテスト工程に統合するよう協力します。 WebGPU実装では、既知のバグへの対応策を講じ、回避困難なバグがあるドライバではWebGPUの利用を無効化することが期待されます。
2.1.7. タイミング攻撃
2.1.7.1. コンテンツ・タイムラインのタイミング
WebGPUはJavaScriptに新しい状態(コンテンツタイムライン)を公開しません。これは、エージェントが
エージェントクラスタ内で共有するものです。
コンテンツタイムラインの状態(例:[[mapping]])は、
明示的なコンテンツタイムラインタスク(通常のJavaScript同様)時のみ変更されます。
2.1.7.2. デバイス/キュー・タイムラインのタイミング
書き込み可能なストレージバッファや他の呼び出し間通信は、キュータイムライン上で高精度タイマー構築に利用される場合があります。
オプション機能"timestamp-query"もGPU操作の高精度タイミングを提供します。セキュリティ・プライバシー対策として、タイミングクエリ値は低精度に揃えられます:詳細はcurrent queue timestampを参照。特に以下の点に注意してください:
-
デバイスタイムラインは通常、複数のオリジンで共有されるプロセスで動作するため、COOP/COEPによるクロスオリジン分離はデバイス/キュー・タイムラインのタイマー分離を提供しません。
-
キュータイムラインの作業はデバイスタイムラインから発行され、GPUハードウェア上で実行される際、CPUプロセスと同様の分離(Meltdown対策など)が保証されない場合があります。
-
GPUハードウェアは一般にSpectre型攻撃には脆弱ではありませんが、WebGPUがソフトウェア実装の場合、共有プロセス上で動作し、分離による対策ができません。
2.1.8. Row hammer攻撃
Row hammerはDRAMセルの状態漏洩を利用する攻撃手法です。GPUでも利用される可能性があります。 WebGPUは特別な対策を持たず、プラットフォームレベルの対策(メモリリフレッシュ間隔短縮など)に依存します。
2.1.9. サービス妨害(DoS)
WebGPUアプリケーションはGPUメモリや計算ユニットへアクセス可能です。WebGPU実装は、他のアプリケーションの応答性維持のため、利用可能なGPUメモリ量を制限する場合があります。 GPU処理時間については、アプリケーションが数秒以上GPUの応答を止めないよう「ウォッチドッグ」タイマーを設けることもできます。 これらの対策はWebGLでも用いられています。
2.1.10. ワークロード識別
WebGPUは同一マシン上で動作する他プログラム(Webページ)と共有される制約付きグローバルリソースへアクセスします。アプリケーションは、これら共有リソースの利用パターンから、他ページで実行中のワークロードを間接的に推測することが可能です。 これらの問題は、JavascriptでのシステムメモリやCPU実行スループットに関する問題と同様です。WebGPUは追加の対策を提供しません。
2.1.11. メモリリソース
WebGPUは、VRAMなどのマシングローバルメモリヒープからの失敗可能な割り当てを公開します。 これにより、あるヒープ種別の残りメモリ量を、割り当てを試みて失敗を監視することで推測できます。
GPUは内部的に1つ以上(通常は2つのみ)のメモリヒープを、全アプリケーションで共有しています。ヒープが枯渇するとWebGPUはリソース作成に失敗します。 これは観測可能であり、悪意あるアプリケーションが他アプリケーションのヒープ利用状況や割り当て量を推測できる場合があります。
2.1.12. 計算リソース
他サイトが同時にWebGPUを利用すると、処理完了までの時間増加を観測できる場合があります。例えば、サイトが継続的に計算ワークロードをキューへ送り、完了を監視することで、他の何かがGPU利用を開始したことを推測できます。
GPUには演算ユニット、テクスチャサンプリングユニット、アトミックユニット等、個別にテスト可能な多数の部品があります。悪意あるアプリケーションは、これらユニットの負荷状況を感知し、他アプリケーションのワークロードを推測しようとする場合があります。これはJavascriptのCPU実行状況と同様の現実です。
2.1.13. 機能の濫用
悪意あるサイトは、WebGPUが公開する機能を悪用し、ユーザーや体験の利益にならない計算(隠れた暗号通貨マイニング、パスワード解析、レインボーテーブル計算など)を実行する可能性があります。
API利用のこうした用途を防ぐことはできません。ブラウザーが正当なワークロードと悪用ワークロードを区別できないためです。これはWeb上の汎用計算機能(JavaScript、WebAssembly、WebGL)全般に共通する問題で、WebGPUは一部ワークロードの実装・実行を容易または効率化するだけです。
この種の濫用軽減策として、ブラウザーはバックグラウンドタブの操作をスロットリングしたり、リソース大量利用中のタブを警告したり、WebGPU利用可能なコンテキストを制限できます。
ユーザーエージェントは、特に悪意ある利用による高い電力消費に対し、ユーザーへの警告を経験的に発することができます。 そのような警告を実装する場合、JavaScript、WebAssembly、WebGLなどと同様にWebGPUも判断基準に含めるべきです。
2.2. プライバシーの考慮事項
WebGPUのプライバシー考慮事項はWebGLと似ています。GPU APIは複雑であり、開発者が効果的に利用するために、デバイスの機能の様々な側面を必要に応じて公開する必要があります。一般的な対策としては、識別につながる情報を正規化またはビニングし、可能な限り挙動を統一することが含まれます。
ユーザーエージェントは、32個を超える識別可能な構成やバケットを公開してはなりません。
2.2.1. 機器固有の機能と制限
WebGPUは、基盤となるGPUアーキテクチャやデバイス形状に関する多くの詳細を公開できます。 これには利用可能な物理アダプター、GPUやCPUリソースの多数の制限(最大テクスチャサイズなど)、および利用可能なオプションのハードウェア固有機能が含まれます。
ユーザーエージェントは、実際のハードウェア制限を公開する義務はなく、機器固有情報の公開度合いを完全に制御できます。フィンガープリント防止の一手として、すべてのターゲットプラットフォームを少数のビンにまとめる手法があります。全体として、ハードウェア制限の公開によるプライバシーへの影響はWebGLと同等です。
デフォルトの制限値も、ほとんどのアプリケーションがより高い制限を要求せずとも動作できるよう、意図的に十分高く設定されています。 APIの利用は要求された制限値に従い検証されるため、実際のハードウェア機能が偶然ユーザーに露出することはありません。
2.2.2. 機器固有のアーティファクト
WebGLと同様に、機器固有のラスタライズ/精度アーティファクトやパフォーマンス差が観測される場合があります。これにはラスタライズ範囲やパターン、シェーダーステージ間の補間精度、計算ユニットのスケジューリング、その他実行に関する要素が含まれます。
一般に、ラスタライズや精度のフィンガープリントはベンダーごとのほぼ全デバイスで一致します。パフォーマンス差は比較的扱い難いですが、信号としても低い傾向(JS実行性能と同様)です。
プライバシー重視のアプリケーションやユーザーエージェントは、こうしたアーティファクトを除去するためにソフトウェア実装を利用すべきです。
2.2.3. 機器固有のパフォーマンス
ユーザーを識別するもう一つの要素は、GPU上の特定操作の性能測定です。低精度タイミングでも、操作の繰り返し実行により、ユーザーのマシンが特定ワークロードに強いかどうかが判明します。 これはWebGLやJavascriptにも存在する一般的なベクトルですが、信号としては低く、完全な正規化は困難です。
WebGPUの計算パイプラインは、固定機能ハードウェアに妨げられないGPUアクセスを公開します。これによりユニークなデバイスフィンガープリントのリスクが高まります。ユーザーエージェントは論理的なGPU呼び出しと実際の計算ユニットを分離する等の対策でリスク低減が可能です。
2.2.4. ユーザーエージェントの状態
本仕様は、オリジンごとの追加ユーザーエージェント状態を定義していません。
ただし、ユーザーエージェントは高負荷なコンパイル結果(GPUShaderModule、
GPURenderPipeline、
GPUComputePipeline等)のコンパイルキャッシュを持つことが期待されます。
これらのキャッシュはWebGPUアプリケーションの初回訪問後の読み込み時間短縮に重要です。
仕様上は、これらのキャッシュは非常に高速なコンパイルと区別できませんが、アプリケーション側ではcreateComputePipelineAsync()の解決にかかる時間を容易に測定でき、オリジン間で情報漏洩する可能性があります(例:「ユーザーがこの特定のシェーダーでサイトへアクセスしたか」)。そのためユーザーエージェントはストレージ分割のベストプラクティスに従うべきです。
システムのGPUドライバも独自のシェーダーやパイプラインのコンパイルキャッシュを持つ場合があります。ユーザーエージェントは可能な限りこれらを無効化するか、パーティションごとのデータをシェーダーへ加えて、GPUドライバが別物とみなすようにすることもできます。
2.2.5. ドライバのバグ
セキュリティの考慮事項で述べた懸念に加え、ドライバのバグはユーザーの識別手段となる挙動差を生じる場合があります。セキュリティの考慮事項に記載の対策(GPUベンダーとの協調、既知問題へのワークアラウンド実装等)もここで適用されます。
2.2.6. アダプタ識別子
WebGLの過去の経験から、開発者がGPUの種類を特定可能であることが、堅牢なGPUベースコンテンツの作成・保守に正当な必要があることが示されています。例として、既知のドライババグがあるアダプタを特定して回避したり、特定ハードウェアで性能が期待通りでない機能を避けたりする場合などです。
しかしアダプタ識別子の公開はフィンガープリント情報の増加につながるため、識別精度の制限が望まれます。
堅牢なコンテンツとプライバシー保護のバランスを取るため、いくつかの対策が可能です。まず、ユーザーエージェントが既知のドライバ問題を特定し回避することで、開発者の負担を軽減できます(これはブラウザがGPU利用を始めて以来行われています)。
アダプタ識別子をデフォルトで公開する場合、可能な限り幅広く(ベンダーや一般的なアーキテクチャのみ)しつつ有用性を保つべきです。場合によっては、実際のアダプタの合理的な代理となる識別子を報告する場合もあります。
バグ報告など、アダプタの詳細情報が有用な場合は、ユーザーの同意を得て追加情報をページに公開することが可能です。
最後に、ユーザーエージェントは、強化プライバシーモードなど適切と判断した場合、アダプタ識別子を一切報告しない裁量を常に持ちます。
3. 基本事項
3.1. 規約
3.1.1. 構文上の省略形
本仕様では、以下の構文上の省略形を使用します:
.(ドット)構文。プログラミング言語で一般的です。-
「
Foo.Bar」は「値(またはインターフェース)FooのBarメンバー」を意味します。Fooが順序付きマップであり、BarがFooに存在しない場合はundefinedを返します。 ?.(オプショナルチェーン)構文。JavaScript由来です。-
「
Foo?.Bar」は「Fooがnullまたはundefined、またはBarがFooに存在しない場合はundefined、それ以外はFoo.Bar」を意味します。例として、
bufferがGPUBufferの場合、buffer?.\[[device]].\[[adapter]]は 「bufferがnullまたはundefinedならundefined、 それ以外はbufferの\[[device]]内部スロットの\[[adapter]]内部スロット」を指します。 ??(ヌリッシュ合体)構文。JavaScript由来です。-
「
x??y」は「xがnullまたはundefinedでないならx、そうでなければy」です。 - スロットバック属性
-
同名の内部スロットで裏付けられるWebIDL属性です。可変の場合と不可変の場合があります。
3.1.2. WebGPUオブジェクト
WebGPUオブジェクトは、WebGPUインターフェースと内部オブジェクトから構成されます。
WebGPUインターフェースは、WebGPUオブジェクトの公開インターフェースと状態を定義します。 作成されたコンテンツタイムライン上で利用でき、JavaScript公開WebIDLインターフェースです。
GPUObjectBaseを含むインターフェースはすべてWebGPUインターフェースです。
内部オブジェクトは、WebGPUオブジェクトの状態をデバイスタイムライン上で追跡します。 内部オブジェクトの可変状態の読み書きは、単一の順序付けられたデバイスタイムライン上でのみ実行されます。
以下の特別なプロパティ型がWebGPUオブジェクトに定義できます:
- 不変プロパティ
-
オブジェクト初期化時に設定される読み取り専用スロット。任意のタイムラインからアクセスできます。
注意: このスロットは不変なので、必要に応じて複数のタイムラインでコピーを持つことができます。 不変プロパティは、本仕様で複数コピーの記述を避けるためこう定義されています。
[[角括弧付き]]の場合は内部スロット。
角括弧なしの場合はスロットバック属性です。 - コンテンツタイムラインプロパティ
-
オブジェクト作成時のコンテンツタイムラインでのみアクセス可能なプロパティ。
[[角括弧付き]]の場合は内部スロット。
角括弧なしの場合はスロットバック属性です。 - デバイスタイムラインプロパティ
-
内部オブジェクトの状態を追跡し、作成されたデバイスタイムラインでのみアクセス可能なプロパティ。デバイスタイムラインプロパティは可変です。
デバイスタイムラインプロパティは
[[角括弧付き]]で内部スロットです。 - キュータイムラインプロパティ
-
内部オブジェクトの状態を追跡し、作成されたキュータイムラインでのみアクセス可能なプロパティ。キュータイムラインプロパティは可変です。
キュータイムラインプロパティは
[[角括弧付き]]で内部スロットです。
interface mixin GPUObjectBase {attribute USVString label ; };
GPUObjectBase
parent,
interface T, GPUObjectDescriptorBase
descriptor)
(TはGPUObjectBaseを拡張する)
場合、次のコンテンツタイムライン手順を実行する:
-
deviceをparent.
[[device]]とする。 -
objectをTの新しいインスタンスとする。
-
object.
[[device]]にdeviceを設定する。 -
objectを返す。
GPUObjectBase
には以下の不変プロパティがあります:
[[device]]型 device(readonly)-
このオブジェクトの内容への操作はassertで デバイスタイムライン上で動作し、デバイスが有効であることを検証します。
GPUObjectBase
には以下のコンテンツタイムラインプロパティがあります:
label型 USVString-
開発者が指定するラベル。実装定義の方法で利用されます。 ブラウザ、OS、その他ツールが、基盤となる内部オブジェクトを開発者へ識別するために使用可能です。 例:
GPUErrorメッセージ、コンソール警告、ブラウザデベロッパーツール、プラットフォームデバッグユーティリティなどで表示されます。注意:実装はラベルを使ってWebGPUオブジェクトの識別を強化したエラーメッセージを推奨します。ただし、これは唯一の識別方法である必要はありません。 実装は他の利用可能な情報も活用 すべき です。ラベルがない場合など、例えば:
-
GPUTextureの親ラベルをGPUTextureView表示時に利用 -
GPUCommandEncoderの親ラベルをGPURenderPassEncoderやGPUComputePassEncoder表示時に利用 -
GPUCommandEncoderのソースラベルをGPUCommandBuffer表示時に利用 -
GPURenderBundleEncoderのソースラベルをGPURenderBundle表示時に利用
注意:labelはGPUObjectBaseのプロパティです。 2つのGPUObjectBaseラッパーオブジェクトは、同じ基盤オブジェクトを参照していても、ラベル状態は完全に分離しています (例:getBindGroupLayout()で返された場合)。labelプロパティは、JavaScriptから設定された場合のみ変更されます。つまり、1つの基盤オブジェクトが複数ラベルと関連付けられる場合があります。 本仕様ではラベルがデバイスタイムラインに伝搬する方法は定義しません。 ラベルの利用方法は完全に実装定義です。エラーメッセージで最新ラベル、全ラベル、あるいはラベルなしを表示する場合があります。
一部ユーザーエージェントが基盤ネイティブAPIのデバッグ機能にラベルを渡す場合があるため、型は
USVStringです。 -
GPUObjectBase
には以下のデバイスタイムラインプロパティがあります:
[[valid]]型boolean(初期値true)-
trueの場合、内部オブジェクトが有効であることを示します。
[[device]])のガベージコレクションを妨げるべきではありません。ただし、一部実装で親オブジェクトへの強参照が必要な場合は保証できません。
そのため、開発者はWebGPUインターフェースが、そのインターフェースのすべての子オブジェクトがガベージコレクトされるまで、ガベージコレクトされない可能性があると想定すべきです。これにより、一部リソースが予想より長期間割り当てられる場合があります。
割り当てリソースの予測可能な解放が必要な場合は、destroyメソッド(例:GPUDevice.destroy()やGPUBuffer.destroy())の呼び出しを推奨します。ガベージコレクションへの依存は避けてください。
3.1.3. オブジェクト記述子
オブジェクト記述子は、オブジェクトの作成に必要な情報を保持します。
通常、create*メソッド(GPUDeviceのメソッド)を使って作成されます。
dictionary {GPUObjectDescriptorBase USVString label = ""; };
GPUObjectDescriptorBase
のメンバーは以下の通りです:
label、型 USVString、デフォルト値""-
GPUObjectBase.labelの初期値です。
3.2. 非同期性
3.2.1. 無効な内部オブジェクトと伝播する無効性
WebGPUのオブジェクト生成操作はPromiseを返しませんが、内部的には非同期処理です。返されるオブジェクトは内部オブジェクトを参照し、デバイスタイムライン上で操作されます。
例外やリジェクトで失敗するのではなく、多くのエラーは関連するデバイスタイムラインでGPUErrorを生成し、デバイスに通知します。
内部オブジェクトは有効か無効のいずれかです。 無効オブジェクトは後で有効になることはありませんが、 有効オブジェクトが無効化される場合もあります。
作成時にオブジェクトが無効になる場合があります。例えばオブジェクト記述子が有効なオブジェクトを表していない場合や、リソース割り当てに十分なメモリがない場合です。
また、他の無効なオブジェクトから生成した場合(例:無効なGPUTextureに対してcreateView()を呼ぶ場合)も発生します。
このケースは伝播する無効性と呼ばれます。
内部オブジェクトはほとんどの型で作成後に無効になりませんが、使用不能になる場合があります(例:所有デバイスが失われた、destroyedされた、バッファ状態が「destroyed」など)。
一部の型では、作成後に無効になる場合があります。特に、デバイス、アダプター、GPUCommandBuffer、
コマンド/パス/バンドルエンコーダです。
GPUObjectBase
objectがtargetObjectと併用可能(valid to use with)であるとは、以下のデバイスタイムライン条件をすべて満たす場合です:
-
object.
[[valid]]がtrueであること。 -
object.
[[device]].[[valid]]がtrueであること。 -
object.
[[device]]とtargetObject.[[device]]が等しいこと。
3.2.2. Promiseの順序付け
WebGPUのいくつかの操作はPromiseを返します。
WebGPUは、これらのPromiseの解決(resolveまたはreject)順序について、以下を除き保証しません:
-
ある
GPUQueueqに対し、 p1 = q.onSubmittedWorkDone()を先に呼び、 p2 = q.onSubmittedWorkDone()を後で呼んだ場合、p1はp2より先に解決されなければなりません。 -
ある
GPUQueueqと同じGPUDevice上のGPUBufferbに対し、 p1 = b.mapAsync()を先に呼び、 p2 = q.onSubmittedWorkDone()を後で呼んだ場合、p1はp2より先に解決されなければなりません。
アプリケーションは他のPromiseの解決順序に依存してはなりません。
3.3. 座標系
レンダリング操作では、以下の座標系を使用します:
-
正規化デバイス座標(NDC)は3次元座標で、次の範囲です:
-
-1.0 ≤ x ≤ 1.0
-
-1.0 ≤ y ≤ 1.0
-
0.0 ≤ z ≤ 1.0
-
左下隅は(-1.0, -1.0, z)です。
正規化デバイス座標。 注意:
z = 0またはz = 1がニア平面として扱われるかはアプリケーション依存です。上記図はz = 0をニア平面としていますが、実際の挙動はシェーダーで使う投影行列、depthClearValue、depthCompare関数等の組み合わせで決まります。 -
-
クリップ空間座標は4次元(x, y, z, w)です。
-
フレームバッファ座標は、フレームバッファ内のピクセルを指定します。
-
2次元座標です。
-
各ピクセルはx・y方向に1単位分広がります。
-
左上隅は(0.0, 0.0)です。
-
xは右方向へ増加します。
-
yは下方向へ増加します。
-
詳細は§ 17 レンダーパス、§ 23.2.5 ラスタライズを参照。
フレームバッファ座標。 -
-
ビューポート座標は、x・y方向でフレームバッファ座標、z方向で深度を持ちます。
-
通常は0.0 ≤ z ≤ 1.0ですが、
[[viewport]].minDepthやmaxDepthをsetViewport()で設定することで変更できます。
-
-
フラグメント座標はビューポート座標と一致します。
-
テクスチャ座標(2DではUV座標とも呼ばれる)は、テクスチャのサンプリングで使われ、
texture dimensionに応じた成分数を持ちます。-
0 ≤ u ≤ 1.0
-
0 ≤ v ≤ 1.0
-
0 ≤ w ≤ 1.0
-
(0.0, 0.0, 0.0)はテクスチャメモリアドレス順で最初のテクセルです。
-
(1.0, 1.0, 1.0)はテクスチャメモリアドレス順で最後のテクセルです。
2Dテクスチャ座標。 -
-
ウィンドウ座標または表示座標は、フレームバッファ座標と一致し、外部ディスプレイや類似のインターフェースとのやり取り時に使われます。
注意: WebGPUの座標系はDirectXのグラフィックスパイプラインの座標系に一致します。
3.4. プログラミングモデル
3.4.1. タイムライン
WebGPUの挙動は「タイムライン」で記述されます。 各操作(アルゴリズムとして定義)は、タイムライン上で実行されます。 タイムラインは、操作の順序と、どの状態がどの操作から参照できるかを明確に定義します。
注意: この「タイムライン」モデルは、ブラウザエンジンのマルチプロセスモデル(通常「コンテンツプロセス」と「GPUプロセス」)や、 多くの実装でGPU自体が独立した実行ユニットであることに由来する制約を記述します。 WebGPUの実装は、タイムラインで並列実行する必要はないため、複数プロセスやスレッドは必須ではありません。 (ただし、get a copy of the image contents of a contextのように、他タイムラインの完了を同期的に待つ場合は並行処理が必要です。)
- コンテンツタイムライン
-
Webスクリプトの実行に関連付けられます。 本仕様で記載されているすべてのメソッド呼び出しを含みます。
ある
GPUDevicedeviceの操作でコンテンツタイムラインへ手順を発行するには、 queue a global task for GPUDevicedeviceでその手順を発行します。 - デバイスタイムライン
-
ユーザーエージェントが発行するGPUデバイス操作に関連付けられます。 アダプター、デバイス、GPUリソースや状態オブジェクトの作成を含みます。これらは通常、GPUを制御するユーザーエージェント側から見ると同期的ですが、別プロセスで実行されることもあります。
- キュータイムライン
-
GPUの計算ユニット上での操作の実行に関連付けられます。実際の描画、コピー、計算ジョブなどGPU上で実行される処理を含みます。
- タイムライン非依存
-
上記いずれかのタイムラインに関連します。
不変プロパティimmutable propertiesや 呼び出し元から渡された引数のみを操作する場合、どのタイムラインにも手順を発行できます。
- 不変値例用語 定義
-
すべてのタイムラインで利用可能です。
- コンテンツタイムライン例用語 定義
-
コンテンツタイムラインのみで利用可能です。
- デバイスタイムライン例用語 定義
-
デバイスタイムラインのみで利用可能です。
- キュータイムライン例用語 定義
-
キュータイムラインのみで利用可能です。
不変値例用語の利用例。 コンテンツタイムライン例用語の利用例。
不変値例用語の利用例。 デバイスタイムライン例用語の利用例。
不変値例用語の利用例。 キュータイムライン例用語の利用例。
本仕様では、非同期操作は戻り値がコンテンツタイムライン以外のタイムラインで行われる処理に依存する場合に使われます。 APIではPromiseやイベントで表現されます。
GPUComputePassEncoder.dispatchWorkgroups():
-
ユーザーは
dispatchWorkgroupsコマンドをGPUComputePassEncoderのメソッドで呼び出し、コンテンツタイムライン上でエンコードされます。 -
ユーザーは
GPUQueue.submit()を呼び、GPUCommandBufferをユーザーエージェントに渡します。これはOSドライバによる低レベルのサブミットとしてデバイスタイムライン上で処理されます。 -
サブミットはGPUの呼び出しスケジューラによって実際の計算ユニットへ割り当てられ、キュータイムライン上で実行されます。
GPUDevice.createBuffer():
-
ユーザーは
GPUBufferDescriptorを記入し、GPUBufferを作成します。 これはコンテンツタイムライン上で行われます。 -
ユーザーエージェントはデバイスタイムライン上で低レベルのバッファを作成します。
GPUBuffer.mapAsync():
-
ユーザーは
GPUBufferのマップをコンテンツタイムライン上でリクエストし、Promiseが返されます。 -
ユーザーエージェントはバッファがGPUで現在使用中かどうかを確認し、使用終了後に再確認するリマインダーを設定します。
-
GPUがキュータイムライン上でバッファの使用を終えた後、ユーザーエージェントがメモリへのマッピングを行い、Promiseをresolveします。
3.4.2. メモリモデル
このセクションは規定ではありません。
アプリケーション初期化時にGPUDeviceを取得したら、
WebGPUプラットフォームは以下のレイヤーで構成されると記述できます:
-
本仕様を実装するユーザーエージェント。
-
このデバイス用の低レベルネイティブAPIドライバを持つオペレーティングシステム。
-
実際のCPUおよびGPUハードウェア。
WebGPUプラットフォームの各レイヤーは、 ユーザーエージェントが仕様実装時に考慮すべき異なるメモリ型を持つ場合があります:
-
スクリプト所有のメモリ(
ArrayBufferなど)は、通常GPUドライバからはアクセスできません。 -
ユーザーエージェントが、コンテンツ実行とGPUドライバ通信をそれぞれ別プロセスで行う場合、プロセス間共有メモリを用いてデータを転送します。
-
専用GPUは高速な独自メモリを持ち、統合GPUは通常システムメモリを共有します。
ほとんどの物理リソースは、 GPUによる計算やレンダリングに効率的なメモリ型で割り当てられます。 ユーザーがGPUに新しいデータを提供する必要がある場合、データがプロセス境界を越えてGPUドライバと通信するユーザーエージェント部分へ届き、 さらにドライバに見えるようにする必要があります(これはドライバ割り当てのステージングメモリへのコピーを伴う場合もあります)。 最後に、専用GPUメモリへ転送され、内部レイアウトがGPU操作に最適な形へ変換されることもあります。
これらすべての遷移は、ユーザーエージェントによるWebGPU実装で処理されます。
注意: この例は最悪ケースを記述していますが、実際の実装ではプロセス境界を越えない場合や、
ドライバ管理メモリをArrayBufferとして直接公開し、データコピーを回避できる場合もあります。
3.4.3. リソースの使用法
物理リソースは、内部使用法としてGPUコマンドで利用できます。
- input
-
描画やディスパッチ呼び出しの入力データ用バッファ。内容は保持されます。 buffer
INDEX、 bufferVERTEX、 bufferINDIRECTで許可されます。 - constant
-
シェーダーから見て定数となるリソースバインディング。内容は保持されます。 buffer
UNIFORMまたは textureTEXTURE_BINDINGで許可されます。 - storage
-
読み書き可能なストレージリソースバインディング。 buffer
STORAGEまたは textureSTORAGE_BINDINGで許可されます。 - storage-read
-
読み取り専用ストレージリソースバインディング。内容は保持されます。 buffer
STORAGEまたは textureSTORAGE_BINDINGで許可されます。 - attachment
-
レンダーパスで読み書き出力アタッチメントや書き込み専用リゾルブターゲットとして使うテクスチャ。 texture
RENDER_ATTACHMENTで許可されます。 - attachment-read
-
レンダーパスで読み取り専用アタッチメントとして使うテクスチャ。内容は保持されます。 texture
RENDER_ATTACHMENTで許可されます。
サブリソースは、バッファ全体またはテクスチャのサブリソースです。
-
Uの各使用法がinput、constant、storage-read、attachment-readのいずれかである。
-
Uの各使用法がstorageである。
複数の書き込み可能な使用法も許可されます。 これは使用法範囲ストレージ例外です。
-
Uの各使用法がattachmentである。
複数の書き込み可能な使用法も許可されます。 これは使用法範囲アタッチメント例外です。
使用法が互換使用法リストにだけ組み合わされるよう強制することで、APIはメモリ操作のデータ競合発生タイミングを制限できます。 この性質により、WebGPU向けに書かれたアプリケーションが異なるプラットフォームでも修正なしで動作しやすくなります。
-
すべてのアスペクトを読み取り専用にした深度/ステンシルアタッチメント(
depthReadOnlyやstencilReadOnlyを指定)。 -
描画呼び出しでのテクスチャバインディング。
-
バッファまたはテクスチャをstorageとして2つの異なる描画呼び出しでレンダーパスにバインド可能。
-
1つのバッファの非重複範囲を2つの異なるバインディングポイントにstorageとしてバインド可能。
重複範囲は1つのディスパッチ/描画呼び出しにバインド不可です。これは"Encoder bind groups alias a writable resource"で検証されます。
同じスライスを2つの異なるアタッチメントに重複してバインド不可です。これはbeginRenderPass()で検証されます。
3.4.4. 同期
使用法範囲は、マップであり、サブリソースからlist<内部使用法>>への対応です。 各使用法範囲は、互いに同時実行可能な一連の操作範囲をカバーし、その範囲内ではサブリソースの使用法が一貫した互換使用法リストでなければなりません。
使用法範囲はエンコード時に構築・検証されます:
使用法範囲は以下の通り:
-
計算パスでは、各ディスパッチコマンド(
dispatchWorkgroups()やdispatchWorkgroupsIndirect()) が1つの使用法範囲です。サブリソースは、ディスパッチでアクセス可能性がある場合に使用されます。例:
-
現在の
GPUComputePipelineの[[layout]]でバインドグループから参照されるすべてのサブリソース -
ディスパッチ呼び出しで直接使われるバッファ(例:インダイレクトバッファ)
注意: 計算パスの状態設定コマンド(setBindGroup()など)は、 バインドしたリソース自体を使用法範囲に直接加えません。ディスパッチコマンド時に状態が参照されて検証されます。
-
-
1つのレンダーパスが1つの使用法範囲です。
サブリソースは、状態設定コマンドも含め、任意のコマンドで参照された場合に使用法範囲として扱われます(計算パスと異なり)。例:
-
setVertexBuffer()で設定されたバッファ -
setIndexBuffer()で設定されたバッファ -
setBindGroup()で設定されたバインドグループから参照されるすべてのサブリソース
-
描画呼び出しで直接使われるバッファ(例:インダイレクトバッファ)
-
注意: コピーコマンドは単独の操作であり、使用法範囲検証には使いません。自己競合防止のため独自検証を行います。
-
レンダーパスでは、パイプラインのシェーダーやレイアウトがこれらバインディングに依存しているか、バインドグループが別のset呼び出しで上書きされているかに関係なく、任意のsetBindGroup()呼び出しで使われるサブリソース。
-
描画呼び出しがこのバッファを利用するか、他のset呼び出しで上書きされているかに関係なく、任意の
setVertexBuffer()呼び出しで使われるバッファ。 -
描画呼び出しがこのバッファを利用するか、他のset呼び出しで上書きされているかに関係なく、任意の
setIndexBuffer()呼び出しで使われるバッファ。 -
GPURenderPassDescriptorのカラーアタッチメント、リゾルブアタッチメント、深度/ステンシルアタッチメントで使われるテクスチャサブリソース(beginRenderPass()で参照)、シェーダーがこれらアタッチメントに依存しているか否かに関係なく。 -
可視性0のバインドグループエントリで使われるリソース、および計算ステージのみ可視でレンダーパスで使われる(またはその逆)リソース。
3.5. コア内部オブジェクト
3.5.1. アダプター
アダプターは、システム上のWebGPU実装を識別します。 これは、ブラウザの基盤となるプラットフォーム上の計算/レンダリング機能のインスタンス、そしてその機能上に構築されたブラウザのWebGPU実装のインスタンスの両方を指します。
アダプターは GPUAdapter
で公開されます。
アダプターは基盤実装を一意に表しません。
requestAdapter()
を複数回呼ぶと、毎回異なるアダプターオブジェクトが返されます。
各アダプターオブジェクトは、1つのデバイスしか生成できません。
requestDevice()
に成功すると、アダプターの[[state]]
は"consumed"
に変化します。
さらに、アダプターオブジェクトはいつでも期限切れになる場合があります。
注意:
これにより、アプリケーションはデバイス生成時に最新のシステム状態を利用したアダプター選択を行えます。
また、初回初期化、アダプターの抜き差しによる再初期化、テスト用のGPUDevice.destroy()
呼び出しによる再初期化など、様々なシナリオで堅牢性が高まります。
アダプターは、広い互換性・予測可能な挙動・プライバシー向上などを目的に、著しい性能低下を伴う場合、フォールバックアダプターと見なされる場合があります。すべてのシステムでフォールバックアダプターが利用可能である必要はありません。
[[features]]型 ordered set<GPUFeatureName> (読み取り専用)-
このアダプター上でデバイス生成に利用可能な機能。
[[limits]]型 supported limits (読み取り専用)-
このアダプター上でデバイス生成に利用可能な最良の制限値。
各アダプター制限値は、supported limits内のデフォルト値と同等またはより良い値でなければなりません。
[[fallback]]型boolean(読み取り専用)-
trueの場合、このアダプターはフォールバックアダプターです。 [[xrCompatible]]型 boolean-
trueの場合、このアダプターはWebXRセッションとの互換性を持つようにリクエストされたことを示します。
アダプターには次のデバイスタイムラインプロパティがあります:
[[state]]初期値"valid"-
"valid"-
このアダプターはデバイス生成に利用可能です。
"consumed"-
このアダプターはすでにデバイス生成に利用されており、再利用できません。
"expired"-
このアダプターは他の理由で期限切れになっています。
GPUAdapter
adapterを期限切れにするには、以下のデバイスタイムライン手順を実行します:
-
adapter.
[[adapter]].[[state]]に"expired"を設定する。
3.5.2. デバイス
デバイスは、アダプターの論理的インスタンスであり、 これを通じて内部オブジェクトが生成されます。
デバイスは、そこから生成されたすべての内部オブジェクトの排他的な所有者です。
デバイスが無効(失われたまたは destroyed)になると、
それとその上で生成されたすべてのオブジェクト(直接:createTexture()、間接:createView()など)は、
暗黙的に利用不可となります。
[[adapter]]型 アダプター (読み取り専用)-
このデバイスが生成されたアダプターです。
[[features]]型 ordered set<GPUFeatureName> (読み取り専用)-
このデバイス上で利用できる機能(生成時に算出)。 基盤アダプターが他の機能をサポートしていても、追加機能は利用できません。
[[limits]]型 supported limits (読み取り専用)-
このデバイスで利用できる制限値(生成時に算出)。 基盤アダプターがより良い制限値をサポートしていても、追加利用はできません。
デバイスには以下のコンテンツタイムラインプロパティがあります:
[[content device]]型GPUDevice(読み取り専用)-
このデバイスに関連付けられたコンテンツタイムラインの
GPUDeviceインターフェース。
GPUDeviceDescriptor
descriptor で
新しいデバイスを生成するには、以下のデバイスタイムライン手順を実行します:
-
featuresを descriptor.
requiredFeaturesの値からなるセットとする。 -
features に
"texture-formats-tier2"が含まれていれば:-
追加で
"texture-formats-tier1"を features に加える。
-
-
features に
"texture-formats-tier1"が含まれていれば:-
追加で
"rg11b10ufloat-renderable"を features に加える。
-
-
追加で
"core-features-and-limits"を features に加える。 -
limitsを、すべての値がデフォルト値に設定されたsupported limitsオブジェクトとする。
-
descriptor.
requiredLimitsの各(key, value)ペアについて:-
valueが
undefinedでなく、かつlimits[key]より良い場合:-
limits[key]にvalueを設定。
-
-
-
deviceをデバイスオブジェクトとする。
-
device.
[[adapter]]にadapterを設定。 -
device.
[[features]]にfeaturesを設定。 -
device.
[[limits]]にlimitsを設定。 -
deviceを返す。
ユーザーエージェントがデバイスへのアクセスを取り消す必要がある場合は、
lose the
device(device, "unknown")
をデバイスのデバイスタイムライン上で呼び出します。
この操作は、同タイムライン上でキューされている他の操作よりも先に実行される場合があります。
操作が失敗し、その副作用がデバイス上のオブジェクトの状態を可視的に変化させたり、内部実装/ドライバ状態を破損する可能性がある場合は、 その変更が可視化されるのを防ぐため、デバイスを失うべきです。
注意:
アプリケーションが(destroy()で)明示的に開始しないすべてのデバイス喪失については、
ユーザーエージェントはlostプロミスが処理されている場合でも、開発者向け警告を無条件で表示するべきです。
これらのシナリオは稀であるべきですが、WebGPU APIの多くがアプリケーションのランタイムフローを中断しないため(検証エラーなし、ほとんどのPromiseは通常通り解決)、シグナルは開発者にとって重要です。
-
無効化でdeviceを無効にする。
-
device.
[[content device]]のコンテンツタイムラインで以下の手順を発行する: -
deviceが失われた状態になるまで待機している未完了手順を完了する。
注意: 失われたデバイスからはエラーは生成されません。 詳細は§ 22 エラーとデバッグを参照。
-
デバイスタイムラインがeventの完了を通知された場合、または
その場合は、timeline上でstepsを発行する。
3.6. オプション機能
WebGPUのアダプターやデバイスは機能を持ちます。 これは、WebGPUの機能が実装ごとに異なることを示すもので、主にハードウェアやシステムソフトウェアの制約によるものです。 機能は機能(feature)または制限(limit)のいずれかです。
ユーザーエージェントは、32個を超える識別可能な構成やバケットを公開してはなりません。
アダプターの機能は§ 4.2.1 アダプター機能保証に準拠しなければなりません。
サポートされている機能だけがrequestDevice()で要求可能です。
サポートされていない機能を要求すると失敗します。
デバイスの機能は"新しいデバイス"で決定され、アダプターのデフォルト(機能なし・デフォルトのsupported
limits)から始まり、requestDevice()で要求された機能が加えられます。
これらの機能は、アダプターの機能に関係なく強制されます。
プライバシーの考慮事項については § 2.2.1 機器固有の機能と制限 を参照してください。
3.6.1. 機能
機能は、すべての実装でサポートされているわけではないWebGPUのオプション機能セットです。主にハードウェアやシステムソフトウェアの制約により左右されます。
すべての機能はオプションですが、アダプターはその可用性についてある程度の保証をします(§ 4.2.1 アダプター機能保証参照)。
デバイスは、生成時に決定された機能のみをサポートします(§ 3.6 オプション機能参照)。 API呼び出しは、これらの機能(アダプターの機能ではなく)に従って検証を行います。
-
既存のAPIサーフェスを新しい方法で利用すると、通常は検証エラーとなります。
-
複数種類のオプションAPIサーフェスがあります:
-
新しいメソッドやenum値を使うと常に
TypeErrorを投げます。 -
新しい辞書メンバーを型が正しい非デフォルト値で使うと、通常は検証エラーとなります。
-
新しいWGSLの
enableディレクティブを使うと、常にcreateShaderModule()で検証エラーとなります。
-
GPUFeatureName
featureが有効(enabled
for)であるとは、
GPUObjectBase
objectにおいて、
object.[[device]].[[features]]
がfeatureを含む場合のみです。
各機能が有効にする機能内容の説明は機能一覧を参照してください。
注意: 機能を有効化することが必ずしも望ましいとは限りません。有効化によってパフォーマンスに影響が出る場合があります。 このため、またデバイスや実装間の移植性向上のため、アプリケーションは実際に必要となる機能のみを要求するべきです。
3.6.2. 制限
制限は、デバイス上でWebGPUを利用する際の数値的な制約です。
注意: 「より良い」制限値を設定することが必ずしも望ましいとは限りません。パフォーマンスに影響が出る場合があります。 このため、また移植性向上のため、アプリケーションは本当に必要な場合のみデフォルトより良い制限値を要求するべきです。
各制限にはデフォルト値があります。
アダプターは常にデフォルトまたはより良い制限値をサポートすることが保証されています(§ 4.2.1 アダプター機能保証参照)。
デバイスは生成時に決定された制限値のみをサポートします(§ 3.6 オプション機能参照)。 API呼び出しは、これらの制限値(アダプターの制限値ではなく)に従って検証されます。より良い/悪い値は利用できません。
任意の制限値について、ある値は他の値よりも優れている場合があります。 優れている制限値は常に検証を緩和し、より多くのプログラムが有効となります。各制限クラスごとに「優れている」の定義があります。
制限値ごとに異なる制限クラスがあります:
- 最大値
-
制限はAPIへ渡される値の最大値を強制します。
高い値ほどより良い値です。
- アライメント
-
制限はAPIへ渡される値の最小アライメント(値は制限値の倍数でなければならない)を強制します。
低い値ほどより良い値です。
設定できるのはデフォルト値以下かつ2の累乗(≤ デフォルト値)のみです。 2の累乗でない値は無効です。 より高い2の累乗値はデフォルト値に丸められます。
supported limitsオブジェクトは、WebGPUで定義されるすべての制限値を保持します:
| 制限名 | 型 | 制限クラス | デフォルト値 |
|---|---|---|---|
maxTextureDimension1D
| GPUSize32
| 最大値 | 8192 |
size.width
に指定できる最大値(テクスチャでdimension
"1d"指定時)。
| |||
maxTextureDimension2D
| GPUSize32
| 最大値 | 8192 |
size.widthおよび
size.height
に指定できる最大値(テクスチャで
dimension
"2d"指定時)。
| |||
maxTextureDimension3D
| GPUSize32
| 最大値 | 2048 |
size.width、
size.height
およびsize.depthOrArrayLayers
に指定できる最大値(テクスチャで
dimension
"3d"指定時)。
| |||
maxTextureArrayLayers
| GPUSize32
| 最大値 | 256 |
size.depthOrArrayLayers
に指定できる最大値(テクスチャで
dimension
"2d"指定時)。
| |||
maxBindGroups
| GPUSize32
| 最大値 | 4 |
GPUBindGroupLayouts
をbindGroupLayouts
に指定できる最大数(GPUPipelineLayout作成時)。
| |||
maxBindGroupsPlusVertexBuffers
| GPUSize32
| 最大値 | 24 |
バインドグループと頂点バッファスロットの同時利用最大数(空スロットも含む、最大インデックス以下のすべて)。createRenderPipeline()やdraw呼び出しで検証される。
| |||
maxBindingsPerBindGroup
| GPUSize32
| 最大値 | 1000 |
GPUBindGroupLayout作成時に利用できるバインディングインデックス数。
注意: この制限は規定ですが任意です。
デフォルトのバインディングスロット制限では、1つのバインドグループで1000個のバインディングは実際には利用不可能ですが、
| |||
maxDynamicUniformBuffersPerPipelineLayout
| GPUSize32
| 最大値 | 8 |
GPUBindGroupLayoutEntry
のうち、動的オフセット付きユニフォームバッファがGPUPipelineLayout全体で利用できる最大数。
バインディングスロット制限を超える場合を参照。
| |||
maxDynamicStorageBuffersPerPipelineLayout
| GPUSize32
| 最大値 | 4 |
GPUBindGroupLayoutEntry
のうち、動的オフセット付きストレージバッファがGPUPipelineLayout全体で利用できる最大数。
バインディングスロット制限を超える場合を参照。
| |||
maxSampledTexturesPerShaderStage
| GPUSize32
| 最大値 | 16 |
各GPUShaderStage
stageごとに、
GPUBindGroupLayoutEntry
のうちサンプリングテクスチャがGPUPipelineLayout全体で利用できる最大数。
バインディングスロット制限を超える場合を参照。
| |||
maxSamplersPerShaderStage
| GPUSize32
| 最大値 | 16 |
各GPUShaderStage
stageごとに、
GPUBindGroupLayoutEntry
のうちサンプラーがGPUPipelineLayout全体で利用できる最大数。
バインディングスロット制限を超える場合を参照。
| |||
maxStorageBuffersPerShaderStage
| GPUSize32
| 最大値 | 8 |
各GPUShaderStage
stageごとに、
GPUBindGroupLayoutEntry
のうちストレージバッファがGPUPipelineLayout全体で利用できる最大数。
バインディングスロット制限を超える場合を参照。
| |||
maxStorageTexturesPerShaderStage
| GPUSize32
| 最大値 | 4 |
各GPUShaderStage
stageごとに、
GPUBindGroupLayoutEntry
のうちストレージテクスチャがGPUPipelineLayout全体で利用できる最大数。
バインディングスロット制限を超える場合を参照。
| |||
maxUniformBuffersPerShaderStage
| GPUSize32
| 最大値 | 12 |
各GPUShaderStage
stageごとに、
GPUBindGroupLayoutEntry
のうちユニフォームバッファがGPUPipelineLayout全体で利用できる最大数。
バインディングスロット制限を超える場合を参照。
| |||
maxUniformBufferBindingSize
| GPUSize64
| 最大値 | 65536 バイト |
GPUBufferBinding.size
の最大値(
GPUBindGroupLayoutEntry
entry の
entry.buffer?.type
が "uniform"
の場合)。
| |||
maxStorageBufferBindingSize
| GPUSize64
| 最大値 | 134217728 バイト (128 MiB) |
GPUBufferBinding.size
の最大値(
GPUBindGroupLayoutEntry
entry の
entry.buffer?.type
が "storage"
または "read-only-storage"
の場合)。
| |||
minUniformBufferOffsetAlignment
| GPUSize32
| アライメント | 256 バイト |
GPUBufferBinding.offset
および setBindGroup()で指定する動的オフセットのアライメント(
GPUBindGroupLayoutEntry
entry の
entry.buffer?.type
が "uniform"
の場合)。
| |||
minStorageBufferOffsetAlignment
| GPUSize32
| アライメント | 256 バイト |
GPUBufferBinding.offset
および setBindGroup()で指定する動的オフセットのアライメント(
GPUBindGroupLayoutEntry
entry の
entry.buffer?.type
が "storage"
または "read-only-storage"
の場合)。
| |||
maxVertexBuffers
| GPUSize32
| 最大値 | 8 |
buffers
の最大数(GPURenderPipeline作成時)。
| |||
maxBufferSize
| GPUSize64
| 最大値 | 268435456 バイト (256 MiB) |
size
の最大値(GPUBuffer作成時)。
| |||
maxVertexAttributes
| GPUSize32
| 最大値 | 16 |
attributes
の合計最大数(buffersを含む、GPURenderPipeline作成時)。
| |||
maxVertexBufferArrayStride
| GPUSize32
| 最大値 | 2048 バイト |
arrayStride
の最大値(GPURenderPipeline作成時)。
| |||
maxInterStageShaderVariables
| GPUSize32
| 最大値 | 16 |
| ステージ間通信(頂点出力やフラグメント入力など)の入出力変数の最大数。 | |||
maxColorAttachments
| GPUSize32
| 最大値 | 8 |
GPURenderPipelineDescriptor.fragment.targets、
GPURenderPassDescriptor.colorAttachments、
GPURenderPassLayout.colorFormats
で指定できるカラーアタッチメント最大数。
| |||
maxColorAttachmentBytesPerSample
| GPUSize32
| 最大値 | 32 |
| すべてのカラーアタッチメントに対し、レンダーパイプライン出力データの1サンプル(ピクセルまたはサブピクセル)保持に必要な最大バイト数。 | |||
maxComputeWorkgroupStorageSize
| GPUSize32
| 最大値 | 16384 バイト |
| 計算ステージのworkgroupストレージで利用できる最大バイト数(シェーダーエントリポイントごと)。 | |||
maxComputeInvocationsPerWorkgroup
| GPUSize32
| 最大値 | 256 |
計算ステージのworkgroup_size各次元の積の最大値(シェーダーエントリポイントごと)。
| |||
maxComputeWorkgroupSizeX
| GPUSize32
| 最大値 | 256 |
計算ステージのworkgroup_sizeのX次元最大値(シェーダーエントリポイントごと)。
| |||
maxComputeWorkgroupSizeY
| GPUSize32
| 最大値 | 256 |
計算ステージのworkgroup_sizeのY次元最大値(シェーダーエントリポイントごと)。
| |||
maxComputeWorkgroupSizeZ
| GPUSize32
| 最大値 | 64 |
計算ステージのworkgroup_sizeのZ次元最大値(シェーダーエントリポイントごと)。
| |||
maxComputeWorkgroupsPerDimension
| GPUSize32
| 最大値 | 65535 |
dispatchWorkgroups(workgroupCountX, workgroupCountY, workgroupCountZ)
の引数に指定できる最大値。
| |||
3.6.2.1. GPUSupportedLimits
GPUSupportedLimits
は、アダプターまたはデバイスのサポートされる制限値を公開します。
GPUAdapter.limits
および GPUDevice.limits
を参照してください。
[Exposed =(Window ,Worker ),SecureContext ]interface GPUSupportedLimits {readonly attribute unsigned long ;maxTextureDimension1D readonly attribute unsigned long ;maxTextureDimension2D readonly attribute unsigned long ;maxTextureDimension3D readonly attribute unsigned long ;maxTextureArrayLayers readonly attribute unsigned long ;maxBindGroups readonly attribute unsigned long ;maxBindGroupsPlusVertexBuffers readonly attribute unsigned long ;maxBindingsPerBindGroup readonly attribute unsigned long ;maxDynamicUniformBuffersPerPipelineLayout readonly attribute unsigned long ;maxDynamicStorageBuffersPerPipelineLayout readonly attribute unsigned long ;maxSampledTexturesPerShaderStage readonly attribute unsigned long ;maxSamplersPerShaderStage readonly attribute unsigned long ;maxStorageBuffersPerShaderStage readonly attribute unsigned long ;maxStorageTexturesPerShaderStage readonly attribute unsigned long ;maxUniformBuffersPerShaderStage readonly attribute unsigned long long ;maxUniformBufferBindingSize readonly attribute unsigned long long ;maxStorageBufferBindingSize readonly attribute unsigned long ;minUniformBufferOffsetAlignment readonly attribute unsigned long ;minStorageBufferOffsetAlignment readonly attribute unsigned long ;maxVertexBuffers readonly attribute unsigned long long ;maxBufferSize readonly attribute unsigned long ;maxVertexAttributes readonly attribute unsigned long ;maxVertexBufferArrayStride readonly attribute unsigned long ;maxInterStageShaderVariables readonly attribute unsigned long ;maxColorAttachments readonly attribute unsigned long ;maxColorAttachmentBytesPerSample readonly attribute unsigned long ;maxComputeWorkgroupStorageSize readonly attribute unsigned long ;maxComputeInvocationsPerWorkgroup readonly attribute unsigned long ;maxComputeWorkgroupSizeX readonly attribute unsigned long ;maxComputeWorkgroupSizeY readonly attribute unsigned long ;maxComputeWorkgroupSizeZ readonly attribute unsigned long ; };maxComputeWorkgroupsPerDimension
3.6.2.2. GPUSupportedFeatures
GPUSupportedFeatures
はsetlikeインターフェースです。そのset entriesは、
アダプターまたはデバイスがサポートする機能の
GPUFeatureName
値です。GPUFeatureName
enumのいずれかの文字列しか含めてはなりません。
[Exposed =(Window ,Worker ),SecureContext ]interface GPUSupportedFeatures {readonly setlike <DOMString >; };
GPUSupportedFeatures
のset entries型はDOMStringです。
これは、現行標準の後続リビジョンで追加された有効なGPUFeatureNameで、
ユーザーエージェントがまだ認識しないものでも、正常に扱えるようにするためです。
set entries型が
GPUFeatureNameだった場合、
下記コードはTypeErrorを投げてしまい、falseを返せません:
3.6.2.3. WGSLLanguageFeatures
WGSLLanguageFeatures
はnavigator.gpu.で利用可能なsetlikeインターフェースです。
そのset entriesは、実装がサポートするWGSL言語拡張の文字列名です
(アダプターやデバイスに関係なく判定されます)。
wgslLanguageFeatures
[Exposed =(Window ,Worker ),SecureContext ]interface WGSLLanguageFeatures {readonly setlike <DOMString >; };
3.6.2.4. GPUAdapterInfo
GPUAdapterInfo
はアダプターの識別情報を公開します。
GPUAdapterInfo
のメンバーは、特定値の設定が保証されません。値がない場合、その属性は空文字("")を返します。
どの値を公開するかはユーザーエージェントの裁量であり、端末によっては値が一切設定されないことも十分あり得ます。
したがって、アプリケーションはGPUAdapterInfo
の任意の値や値が未設定の場合も必ず扱えるようにする必要があります。
アダプターのGPUAdapterInfo
はGPUAdapter.info
およびGPUDevice.adapterInfoで公開されます。
この情報は不変です。
あるアダプターに対しては、各GPUAdapterInfo
属性はアクセスするたびに同じ値を返します。
注意:
GPUAdapterInfo
の属性は初回アクセス時点で不変ですが、実装は各属性の公開値を初回アクセスまで遅延決定しても構いません。
注意:
他のGPUAdapterインスタンス(同じ物理アダプターを表していても)でも、
GPUAdapterInfoの値が異なる場合があります。
ただし、特定のイベント(ページが追加の識別情報取得を許可された場合。現行標準では該当イベント定義なし)がない限り、値は同じにすべきです。
プライバシーの考慮事項については § 2.2.6 アダプター識別子 を参照してください。
[Exposed =(Window ,Worker ),SecureContext ]interface GPUAdapterInfo {readonly attribute DOMString vendor ;readonly attribute DOMString architecture ;readonly attribute DOMString device ;readonly attribute DOMString description ;readonly attribute unsigned long subgroupMinSize ;readonly attribute unsigned long subgroupMaxSize ;readonly attribute boolean isFallbackAdapter ; };
GPUAdapterInfo
には以下の属性があります:
vendor, 型 DOMString, 読み取り専用-
アダプターのベンダー名(利用可能な場合)。なければ空文字。
architecture, 型 DOMString, 読み取り専用-
アダプターが属するGPUファミリー・クラス名(利用可能な場合)。なければ空文字。
device, 型 DOMString, 読み取り専用-
アダプターのベンダー固有識別子(利用可能な場合)。なければ空文字。
注意: これはアダプター種別を表す値(例:PCIデバイスID)です。シリアル番号など特定機器一意の値ではありません。
description, 型 DOMString, 読み取り専用-
ドライバが報告するアダプターの人間可読説明(利用可能な場合)。なければ空文字。
注意:
descriptionには整形が一切施されないため、パースは推奨されません。既知のドライバ問題回避など、GPUAdapterInfoで動作変更する場合は、他フィールドを利用すべきです。 subgroupMinSize, 型 unsigned long, 読み取り専用-
"subgroups"機能がサポートされている場合、アダプターの最小サブグループサイズ。 subgroupMaxSize, 型 unsigned long, 読み取り専用-
"subgroups"機能がサポートされている場合、アダプターの最大サブグループサイズ。 isFallbackAdapter, 型 boolean, 読み取り専用-
アダプターがフォールバックアダプターかどうか。
-
adapterInfoを新しい
GPUAdapterInfoとする。 -
ベンダーが判明していれば、adapterInfo.
vendorにベンダー名(正規化識別文字列)を設定する。プライバシー保護のため、ユーザーエージェントは空文字または適当なベンダー名(正規化識別文字列)にしてもよい。 -
アーキテクチャが判明していれば、adapterInfo.
architectureにアダプターが属するファミリー・クラス名(正規化識別文字列)を設定する。プライバシー保護のため、空文字または適当なアーキテクチャ名(正規化識別文字列)でもよい。 -
デバイスが判明していれば、adapterInfo.
deviceにベンダー固有識別子(正規化識別文字列)を設定する。プライバシー保護のため、空文字または適当な識別子(正規化識別文字列)でもよい。 -
説明が判明していれば、adapterInfo.
descriptionにドライバ報告の説明文を設定。プライバシー保護のため、空文字または適当な説明でもよい。 -
"subgroups"がサポートされていれば、subgroupMinSizeに最小サブグループサイズを設定。なければ4とする。注意: プライバシー保護のため、ユーザーエージェントは一部機能をサポートしないか、区別不能でも利用可能な値(例:すべて4にする)を返す場合がある。
-
"subgroups"がサポートされていれば、subgroupMaxSizeに最大サブグループサイズを設定。なければ128とする。注意: プライバシー保護のため、ユーザーエージェントは一部機能をサポートしないか、区別不能でも利用可能な値(例:すべて128にする)を返す場合がある。
-
adapterInfo.
isFallbackAdapterをadapter.[[fallback]]で設定。 -
adapterInfoを返す。
3.7. 拡張文書
「拡張文書」とは、新しい機能を説明する追加文書であり、非規定でありWebGPU/WGSL仕様の一部ではありません。
これらは本仕様を基盤として構築される機能を記述し、多くの場合新しいAPI機能フラグやWGSLのenableディレクティブ、他のドラフトWeb標準との連携を含みます。
WebGPUの実装は拡張機能を公開してはなりません。公開すると仕様違反となります。 新しい機能はWebGPU標準(本ドキュメント)やWGSL仕様に統合されるまで、WebGPU標準の一部にはなりません。
3.8. オリジン制限
WebGPUは画像、動画、キャンバスに保存された画像データへのアクセスを許可します。 シェーダーによってGPUへアップロードされたテクスチャ内容を間接的に推測できるため、クロスドメインメディアの利用には制限があります。
WebGPUは、オリジンがクリーンでない画像ソースのアップロードを禁止します。
これは、WebGPUで描画されたキャンバスのorigin-cleanフラグがfalseになることは決してないことも意味します。
画像・動画要素のCORSリクエスト発行については以下を参照してください:
3.9. タスクソース
3.9.1. WebGPUタスクソース
WebGPUは新しいタスクソース「WebGPUタスクソース」を定義します。
これはuncapturederrorイベントおよびGPUDevice.lostに使用されます。
GPUDevice
deviceに対し、グローバルタスクをキューするには、
コンテンツタイムライン上で手順stepsを使って:
-
グローバルタスクをキューする(WebGPUタスクソースで、deviceを生成したグローバルオブジェクトとstepsを指定)。
3.9.2. 自動期限切れタスクソース
WebGPUは新しいタスクソース「自動期限切れタスクソース」を定義します。 これは特定オブジェクトの自動・タイマーによる期限切れ(破棄)に使用されます:
GPUDevice
deviceに対し、自動期限切れタスクをキューするには、
コンテンツタイムライン上で手順stepsを使って:
-
グローバルタスクをキューする(自動期限切れタスクソースで、deviceを生成したグローバルオブジェクトとstepsを指定)。
自動期限切れタスクソースからのタスクは高優先度で処理すべきです。特に、キューされたらユーザー定義(JavaScript)タスクより先に実行すべきです。
実装ノート: 高優先度の期限切れ「タスク」は、実際のタスクを実行する代わりに、イベントループ処理モデル内の固定ポイントに追加手順を挿入する形でも有効です。
3.10. 色空間とエンコーディング
WebGPUはカラーマネジメントを提供しません。WebGPU内部の値(テクスチャ要素など)はすべて生の数値であり、カラーマネージされた値ではありません。
WebGPUは、カラーマネージされた出力(GPUCanvasConfiguration)や入力
(copyExternalImageToTexture()やimportExternalTexture())と連携します。
したがって、WebGPU数値と外部色値との間で色変換が必要となります。
各インターフェースポイントごとに、WebGPU数値が解釈されるエンコーディング(色空間、伝達関数、アルファ事前乗算)がローカルに定義されます。
WebGPUは、PredefinedColorSpace
enumのすべての色空間を許可します。
各色空間はCSS定義に基づき拡張範囲を持ち、色空間外の値も表現可能です(色度・輝度両方)。
ガマット外の事前乗算RGBA値とは、R/G/Bチャネル値がアルファ値を超えるものです。例:事前乗算sRGB
RGBA値[1.0, 0, 0, 0.5]は(非事前乗算)色[2, 0, 0]で50%アルファを表し、CSSではrgb(srgb 2 0 0 / 50%)。
sRGB色域外の色値同様、これは拡張色空間の定義済み点です(ただしアルファ0の場合は色がありません)。
ただし、この値を可視キャンバスへ出力する場合、結果は未定義です(GPUCanvasAlphaMode
"premultiplied"参照)。
3.10.1. 色空間変換
色は、上記で定義された方法に従い、ある色空間での表現を別の色空間の表現に変換することで変換されます。
元の値にRGBAチャンネルが4つ未満の場合、欠損している緑/青/アルファチャンネルは順に0, 0, 1として補われ、その後に色空間/エンコーディング変換やアルファプリマルチ化処理が行われます。変換後に宛先が4チャンネル未満を必要とする場合は、余分なチャンネルは無視されます。
注意:
グレースケール画像は一般的にその色空間内でRGB値(V, V, V)、またはRGBA値(V, V, V, A)として表現されます。
色は変換中に不可逆的にクランプされません:ある色空間から別の色空間へ変換する際、元の色値が宛先色空間のガマット範囲外の場合は、[0, 1]の範囲外の値になることがあります。例えばsRGBが宛先の場合、元がrgba16floatやDisplay-P3などの広色域だったり、プリマルチプライされてガマット外値を含んでいる場合に発生します。
同様に、元の値が高ビット深度(例:各成分16ビットのPNG)や拡張範囲(例:float16ストレージのcanvas)の場合でも、これらの色は色空間変換を通じて保持され、中間計算の精度も元データの精度以上となります。
3.10.2. 色空間変換省略
色空間・エンコーディング変換の元と先が同じならば、変換は不要です。一般に、変換の任意のステップが恒等関数(no-op)の場合、実装はパフォーマンスのため省略すべきです。
最適なパフォーマンスのため、アプリケーションは色空間やエンコーディング設定を工夫し、必要な変換数を最小化するべきです。
GPUCopyExternalImageSourceInfoの各種画像ソースに関して:
-
ImageBitmapの場合:-
事前乗算は
premultiplyAlphaで制御。 -
色空間は
colorSpaceConversionで制御。
-
-
2Dキャンバスの場合:
-
色空間は
colorSpaceコンテキスト生成属性で制御。
-
WebGLキャンバスの場合:
-
事前乗算は
premultipliedAlphaオプション(WebGLContextAttributes)で制御。 -
色空間は
WebGLRenderingContextBaseのdrawingBufferColorSpace状態で制御。
-
注意: これらの機能に依存する前に、各ブラウザの実装サポート状況を確認してください。
3.11. JavaScriptからWGSLへの数値変換
WebGPU APIのいくつかの部分(pipeline-overridable constants
や
レンダーパスのクリア値)は、WebIDL(double
や float)の数値を受け取り、
WGSL値(bool, i32, u32, f32, f16)へ変換します。
double
またはfloat)を
WGSL型Tへ変換するには、
(TypeErrorを投げる可能性あり)
以下のデバイスタイムライン手順を実行します:
注意: このTypeError
はデバイスタイムラインで生成され、JavaScriptには表出しません。
-
アサート:idlValueは有限値である(
unrestricted doubleやunrestricted floatではないため)。 -
vを、!によるidlValueの ECMAScript値への変換結果とする。
-
- もし T が
boolの場合 -
WGSL
bool値を返します。これは ! を使い v を IDL値型booleanに変換した結果に対応します。注: このアルゴリズムは ECMAScript の値を IDL
doubleやfloatに変換した後に呼ばれます。元の ECMAScript 値が数値でもブール値でもない[]や{}の場合、WGSLboolの結果は、元の値を IDLbooleanに直接変換した場合と異なることがあります。 - もし T が
i32の場合 -
WGSL
i32値を返します。これは?を使いvをIDL値型[EnforceRange]longに変換した結果に対応します。 - もし T が
u32の場合 -
WGSL
u32値を返します。これは?を使いvをIDL値型[EnforceRange]unsigned longに変換した結果に対応します。 - もし T が
f32の場合 - もし T が
f16の場合 -
-
f16(wgslF32)、すなわちWGSLf32値を!でf16に変換した結果(WGSL浮動小数点変換定義)を返す。
注: 値が
f32の範囲内なら、値がf16の範囲外でもエラーは発生しません。
- もし T が
GPUColor
colorをテクスチャフォーマットのテクセル値formatへ変換するには、
(TypeErrorを投げる可能性あり)
以下のデバイスタイムライン手順を実行します:
注意: このTypeError
はデバイスタイムラインで生成され、JavaScriptには表出しません。
-
formatの各コンポーネント(assert:すべて同じ型)は:
- 浮動小数点型または正規化型の場合
-
Tを
f32とする。 - 符号付き整数型の場合
-
Tを
i32とする。 - 符号なし整数型の場合
-
Tを
u32とする。
-
wgslColorをWGSL型
vec4<T>とし、各RGBAチャネル値はcolorの値を ?でWGSL型Tへ変換したもの。 -
wgslColorを§ 23.2.7 出力マージの変換規則でformatへ変換し、結果を返す。
注意: 整数型以外の場合、値の選択は実装定義となる。 正規化型の場合、値は型の範囲にクランプされる。
注意:
つまり、書き込まれる値はWGSLシェーダーがvec4(f32, i32,
u32)として出力した場合と同じになります。
4. 初期化
4.1. navigator.gpu
GPUオブジェクトは
Window
および WorkerGlobalScope
コンテキストで利用でき、Navigator
および WorkerNavigator
インターフェースを通じて navigator.gpu で公開されます。
interface mixin { [NavigatorGPU SameObject ,SecureContext ]readonly attribute GPU gpu ; };Navigator includes NavigatorGPU ;WorkerNavigator includes NavigatorGPU ;
NavigatorGPU
には以下の属性があります:
gpu, 型 GPU, 読み取り専用-
requestAdapter()などトップレベルエントリポイントを提供するグローバルシングルトン。
4.2. GPU
GPUはWebGPUへの入り口です。
[Exposed =(Window ,Worker ),SecureContext ]interface GPU {Promise <GPUAdapter ?>requestAdapter (optional GPURequestAdapterOptions options = {});GPUTextureFormat getPreferredCanvasFormat (); [SameObject ]readonly attribute WGSLLanguageFeatures wgslLanguageFeatures ; };
GPUは以下のメソッドを持ちます:
requestAdapter(options)-
ユーザーエージェントにアダプターを要求します。 ユーザーエージェントはアダプターを返すかどうか選択し、返す場合は指定オプションに従って決定します。
呼び出し元:GPUthis.引数:
GPU.requestAdapter(options)メソッドの引数 パラメータ 型 Nullable Optional 説明 optionsGPURequestAdapterOptions✘ ✔ アダプター選択基準。 戻り値:
Promise<GPUAdapter?>コンテンツタイムライン手順:
-
contentTimelineを現在のコンテンツタイムラインとする。
-
promiseを新しいPromiseとする。
-
initialization stepsをthisのデバイスタイムラインで発行する。
-
promiseを返す。
デバイスタイムライン initialization steps:-
次の手順の要求はすべて満たされなければなりません。
-
options.
featureLevelは 機能レベル文字列でなければなりません。
満たされ、かつユーザーエージェントがアダプター返却を選択した場合:
-
adapterにアダプターを、§ 4.2.2 アダプター選択ルールとoptionsの基準に従い、 § 4.2.1 アダプター機能保証に従って選択・初期化する:
-
adapter.
[[limits]]と adapter.[[features]]をアダプターのサポート機能に応じて設定する。 adapter.[[features]]には"core-features-and-limits"が含まれていなければならない。 -
adapterがフォールバックアダプター基準を満たす場合は adapter.
[[fallback]]をtrueに、それ以外はfalseにする。 -
adapter.
[[xrCompatible]]に options.xrCompatibleを設定する。
-
それ以外の場合:
-
adapterを
nullにする。
-
-
以降の手順をcontentTimelineで発行する。
コンテンツタイムライン手順:-
adapterが
nullでなければ:-
resolveでpromiseを新しい
GPUAdapter(adapterをラップ)で解決する。
-
-
それ以外はresolveでpromiseを
nullで解決する。
-
getPreferredCanvasFormat()-
8bit深度・標準ダイナミックレンジコンテンツ表示に最適な
GPUTextureFormatを返します。 返す値は"rgba8unorm"または"bgra8unorm"のみです。返された値は
formatとしてconfigure()をGPUCanvasContextで呼ぶ際に渡すことで、関連するキャンバスの効率的な表示が保証されます。注意: 画面表示されないキャンバスでは、このフォーマット利用が有利とは限りません。
呼び出し元:GPUthis.戻り値:
GPUTextureFormatコンテンツタイムライン手順:
-
WebGPUキャンバス表示に最適な形式に応じて
"rgba8unorm"または"bgra8unorm"のいずれかを返す。
-
GPUは以下の属性を持ちます:
wgslLanguageFeatures, 型 WGSLLanguageFeatures, 読み取り専用-
サポートされるWGSL言語拡張名。サポートされる言語拡張は自動的に有効化されます。
アダプターはいつでも
期限切れになる可能性があります。システム状態に変更が生じ、requestAdapter()
の結果に影響する場合、ユーザーエージェントはすべての既返却済み
アダプターを期限切れにすべきです。例:
-
物理アダプター追加/削除(抜き差し、ドライバ更新、ハング回復など)
-
システム電源設定変更(ノートPC抜き差し、電源設定変更など)
注意:
ユーザーエージェントは、システム状態変化がなくても(例:アダプター作成後数秒・数分後など)、アダプターを頻繁に期限切れにすることを選択できます。
これにより実際のシステム状態変化の隠蔽や、requestAdapter()
を再度呼び出す必要性の認識向上につながります。
この状況になっても標準的なデバイスロス回復処理で復旧可能です。
4.2.1. アダプター機能保証
GPUAdapter
がrequestAdapter()
で返された場合、以下の保証が必要です:
-
以下のいずれかが必ず真であること:
-
"texture-compression-bc"がサポートされている。 -
"texture-compression-etc2"と"texture-compression-astc"の両方がサポートされている。
-
-
"texture-compression-bc-sliced-3d"がサポートされている場合は、"texture-compression-bc"もサポートされていなければならない。 -
"texture-compression-astc-sliced-3d"がサポートされている場合は、"texture-compression-astc"もサポートされていなければならない。 -
すべてのアライメントクラス制限値は2の累乗でなければならない。
-
maxBindingsPerBindGroupは、(シェーダーステージごとの最大バインディング数 × パイプラインごとの最大シェーダーステージ数)以上でなければならない。ここで:-
シェーダーステージごとの最大バインディング数は (
maxSampledTexturesPerShaderStage+maxSamplersPerShaderStage+maxStorageBuffersPerShaderStage+maxStorageTexturesPerShaderStage+maxUniformBuffersPerShaderStage)。 -
パイプラインごとの最大シェーダーステージ数は
2。これはGPURenderPipelineが頂点・フラグメントシェーダー両方をサポートするためです。
注意:
maxBindingsPerBindGroupは本質的な制限値ではありません。 実装は他の制限値を下げるのではなく、この値を要件に合わせて引き上げるべきです。 -
-
maxBindGroupsはmaxBindGroupsPlusVertexBuffers以下でなければならない。 -
maxVertexBuffersはmaxBindGroupsPlusVertexBuffers以下でなければならない。 -
minUniformBufferOffsetAlignmentおよびminStorageBufferOffsetAlignmentは両方とも32バイト以上でなければならない。注意: 32バイトは
vec4<f64>のアライメントに相当します。WebGPU Shading Language § 14.4.1 アライメントとサイズ参照。 -
maxUniformBufferBindingSizeはmaxBufferSize以下でなければならない。 -
maxStorageBufferBindingSizeはmaxBufferSize以下でなければならない。 -
maxStorageBufferBindingSizeは4バイトの倍数でなければならない。 -
maxVertexBufferArrayStrideは4バイトの倍数でなければならない。 -
maxComputeWorkgroupSizeXはmaxComputeInvocationsPerWorkgroup以下でなければならない。 -
maxComputeWorkgroupSizeYはmaxComputeInvocationsPerWorkgroup以下でなければならない。 -
maxComputeWorkgroupSizeZはmaxComputeInvocationsPerWorkgroup以下でなければならない。 -
maxComputeInvocationsPerWorkgroupはmaxComputeWorkgroupSizeX×maxComputeWorkgroupSizeY×maxComputeWorkgroupSizeZ以下でなければならない。
4.2.2. アダプター選択
GPURequestAdapterOptions
は、ユーザーエージェントに対してアプリケーションに適した構成のヒントを与えます。
dictionary GPURequestAdapterOptions {DOMString featureLevel = "core";GPUPowerPreference powerPreference ;boolean forceFallbackAdapter =false ;boolean xrCompatible =false ; };
enum {GPUPowerPreference "low-power" ,"high-performance" , };
GPURequestAdapterOptions
には以下のメンバーがあります:
featureLevel, 型 DOMString, デフォルト"core"-
アダプター要求の「機能レベル」。
許可される機能レベル文字列値は:
- "core"
-
効果なし。
- "compatibility"
-
効果なし。
注意: この値は将来的に追加検証制約へのオプトイン用途で予約されています。現時点では使用しないでください。
powerPreference, 型 GPUPowerPreference-
システムの利用可能アダプターからどの種類のアダプターを選択するかのヒントを任意で指定します。
このヒント値は選択されるアダプターに影響する場合がありますが、アダプター返却有無には影響しません。
注意: このヒントの主な用途は、マルチGPU環境で使用するGPUを選択することです。 例えば一部ノートPCは低消費電力統合GPUと高性能離散GPUを持ちます。このヒントは選択GPUの電源設定にも影響する場合があります。
注意: バッテリー状態や外部ディスプレイ・着脱式GPUなどのハード構成により、同じpowerPreferenceでも異なるアダプターが選択される場合があります。 一般的には同一ハード構成・状態と
powerPreferenceなら同じアダプターが選ばれる傾向です。以下のいずれかの値:
undefined(未指定時)-
ユーザーエージェントへのヒントなし。
"low-power"-
パフォーマンスより消費電力節約を優先する要求。
注意: 通常、描画性能制約がない場合(例:1fpsのみ描画、簡単なジオメトリやシェーダーのみ、HTMLキャンバス小サイズなど)はこれを使うべきです。 許容されるなら本値利用を推奨します。携帯機器のバッテリ寿命向上に大きく寄与します。
"high-performance"-
消費電力よりパフォーマンスを優先する要求。
注意: この値を選択すると、デバイス生成時、ユーザーエージェントが電力節約のため低消費電力アダプターに切替え、デバイスロスを強制しやすくなります。 本当に必要な場合以外は指定を控えましょう。携帯機器のバッテリ寿命が大幅に低下する場合があります。
forceFallbackAdapter, 型 boolean, デフォルトfalse-
true指定時、フォールバックアダプターのみ返却可能。ユーザーエージェントがrequestAdapter()で フォールバックアダプター未対応ならnullで解決。注意:
requestAdapter()はforceFallbackAdapterがfalseでも他に適切なアダプターがなかった場合やユーザーエージェント判断で フォールバックアダプターを返す場合があります。 フォールバックアダプターでの動作を防ぎたい場合、info.isFallbackAdapter属性を確認してからGPUDeviceを要求してください。 xrCompatible, 型 boolean, デフォルトfalse-
trueに設定すると、WebXRセッション向けの描画に最適なアダプターが返されるべきであることを示します。ユーザーエージェントやシステムがWebXRセッションをサポートしていない場合は、この値はアダプター選択時に無視されることがあります。注意:
xrCompatibleをtrue指定せずアダプター要求した場合、そのGPUDeviceは WebXRセッション用描画に利用できません。
"high-performance"
GPUAdapter
を要求する例:
const gpuAdapter= await navigator. gpu. requestAdapter({ powerPreference: 'high-performance' });
4.3. GPUAdapter
GPUAdapter
はアダプターをカプセル化し、
その機能(featuresやlimits)を記述します。
GPUAdapter
を取得するには、requestAdapter()を使います。
[Exposed =(Window ,Worker ),SecureContext ]interface GPUAdapter { [SameObject ]readonly attribute GPUSupportedFeatures features ; [SameObject ]readonly attribute GPUSupportedLimits limits ; [SameObject ]readonly attribute GPUAdapterInfo info ;Promise <GPUDevice >requestDevice (optional GPUDeviceDescriptor descriptor = {}); };
GPUAdapter
には以下の不変プロパティがあります。
features, 型 GPUSupportedFeatures, 読み取り専用-
this.[[adapter]].[[features]]の値セット。 limits, 型 GPUSupportedLimits, 読み取り専用-
this.[[adapter]].[[limits]]の制限値。 info, 型 GPUAdapterInfo, 読み取り専用-
この
GPUAdapterの下層物理アダプター情報。同一
GPUAdapterに対してはGPUAdapterInfoの値は常に一定です。毎回同じオブジェクトが返されます。初回生成方法:
[[adapter]], 型 adapter, 読み取り専用-
この
GPUAdapterが参照するアダプター。
GPUAdapter
には以下のメソッドがあります:
requestDevice(descriptor)-
これは一度限りの操作であり、デバイスが返されたらアダプターは
"consumed"状態になります。呼び出し元:GPUAdapterthis.引数:
GPUAdapter.requestDevice(descriptor)メソッドの引数 パラメータ 型 Nullable Optional 説明 descriptorGPUDeviceDescriptor✘ ✔ 要求する GPUDeviceの詳細。コンテンツタイムライン手順:
-
contentTimelineを現在のコンテンツタイムラインとする。
-
promiseを新しいPromiseとする。
-
adapterをthis.
[[adapter]]とする。 -
initialization stepsをthisのデバイスタイムラインで発行する。
-
promiseを返す。
デバイスタイムライン initialization steps:-
次のいずれかの要件を満たしていない場合:
-
descriptor.
requiredFeaturesの値セットはadapter.[[features]]の部分集合でなければならない。
満たさない場合、以降の手順をcontentTimelineで実行し終了:
コンテンツタイムライン手順:注意: このエラーは、ブラウザが機能名を全く認識しない(
GPUFeatureName定義にない)場合と同じです。 ブラウザが機能をサポートしない場合と、特定アダプターが機能をサポートしない場合の動作が収束します。 -
-
次のすべての要件を満たさなければなりません:
-
adapter.
[[state]]は"consumed"であってはならない。 -
descriptor.
requiredLimitsの各[key, value](valueがundefinedでないもの)について:-
keyはsupported limitsメンバー名でなければならない。
-
valueはadapter.
[[limits]][key]より良い値であってはならない。
注意: keyが未認識の場合、valueが
undefinedでも開発者向け警告表示を検討すべきです。 -
満たさない場合、以降の手順をcontentTimelineで実行し終了:
コンテンツタイムライン手順:-
rejectでpromiseを
OperationErrorで解決。
-
-
adapter.
[[state]]が"expired"またはユーザーエージェントが要求を満たせない場合:-
deviceを新しいdeviceとする。
-
Lose the device(device,
"unknown"). -
assert:adapter.
[[state]]は"expired"である。注意: この場合、ユーザーエージェントはほぼすべての場合で開発者向け警告表示を検討すべきです。アプリケーションは
requestAdapter()から再初期化ロジックを行うべきです。
それ以外の場合:
-
-
以降の手順をcontentTimelineで発行する。
コンテンツタイムライン手順:-
gpuDeviceを新しい
GPUDeviceインスタンスとする。 -
gpuDevice.
[[device]]にdeviceを設定。 -
device.
[[content device]]にgpuDeviceを設定。 -
resolveでpromiseをgpuDeviceで解決する。
注意: アダプターが要求を満たせずデバイスが既に失われている場合は、device.
lostがpromiseより先に解決されています。
-
GPUDeviceを要求する例:
const gpuAdapter= await navigator. gpu. requestAdapter(); const gpuDevice= await gpuAdapter. requestDevice();
4.3.1. GPUDeviceDescriptor
GPUDeviceDescriptor
はデバイス要求内容を記述します。
dictionary GPUDeviceDescriptor :GPUObjectDescriptorBase {sequence <GPUFeatureName >requiredFeatures = [];record <DOMString , (GPUSize64 or undefined )>requiredLimits = {};GPUQueueDescriptor defaultQueue = {}; };
GPUDeviceDescriptor
には以下のメンバーがあります:
requiredFeatures, 型 sequence<GPUFeatureName>、デフォルト[]-
デバイス要求で必要な機能を指定します。 アダプターがこれら機能を提供できない場合、要求は失敗します。
API呼び出しの検証では、指定した機能セットのみが利用可能であり、それ以外は利用不可です。
requiredLimits, 型record<DOMString, (GPUSize64 or undefined)>、デフォルト{}-
デバイス要求で必要な制限値を指定します。 アダプターがこれら制限値を提供できない場合、要求は失敗します。
値が
undefinedでない各キーはsupported limitsメンバー名でなければなりません。生成されたデバイスのAPI呼び出しは、そのデバイスの厳密な制限値に従って検証されます(アダプターの制限値ではない。§ 3.6.2 制限参照)。
defaultQueue, 型 GPUQueueDescriptor、デフォルト{}-
デフォルト
GPUQueueの記述内容。
"texture-compression-astc"機能付きGPUDeviceを要求する例:
const gpuAdapter= await navigator. gpu. requestAdapter(); const requiredFeatures= []; if ( gpuAdapter. features. has( 'texture-compression-astc' )) { requiredFeatures. push( 'texture-compression-astc' ) } const gpuDevice= await gpuAdapter. requestDevice({ requiredFeatures});
maxColorAttachmentBytesPerSample制限付きGPUDeviceを要求する例:
const gpuAdapter= await navigator. gpu. requestAdapter(); if ( gpuAdapter. limits. maxColorAttachmentBytesPerSample< 64 ) { // 希望の制限値が未サポートの場合、より高い制限値を必要としないコードパスへフォールバックするか、 // デバイスが最低要件を満たしていないことをユーザーに通知するなどの対応を取る。 } // max color attachments bytes per sampleのより高い制限値を要求。 const gpuDevice= await gpuAdapter. requestDevice({ requiredLimits: { maxColorAttachmentBytesPerSample: 64 }, });
4.3.1.1. GPUFeatureName
各GPUFeatureNameは、
利用可能であればWebGPUの追加利用を許可する機能セットを識別します。
enum GPUFeatureName {"core-features-and-limits" ,"depth-clip-control" ,"depth32float-stencil8" ,"texture-compression-bc" ,"texture-compression-bc-sliced-3d" ,"texture-compression-etc2" ,"texture-compression-astc" ,"texture-compression-astc-sliced-3d" ,"timestamp-query" ,"indirect-first-instance" ,"shader-f16" ,"rg11b10ufloat-renderable" ,"bgra8unorm-storage" ,"float32-filterable" ,"float32-blendable" ,"clip-distances" ,"dual-source-blending" ,"subgroups" ,"texture-formats-tier1" ,"texture-formats-tier2" ,"primitive-index" , };
4.4. GPUDevice
GPUDevice
はデバイスをカプセル化し、その機能を公開します。
GPUDeviceは
WebGPUインターフェースを生成するトップレベルインターフェースです。
GPUDeviceを取得するには、requestDevice()を使用します。
[Exposed =(Window ,Worker ),SecureContext ]interface GPUDevice :EventTarget { [SameObject ]readonly attribute GPUSupportedFeatures features ; [SameObject ]readonly attribute GPUSupportedLimits limits ; [SameObject ]readonly attribute GPUAdapterInfo adapterInfo ; [SameObject ]readonly attribute GPUQueue queue ;undefined destroy ();GPUBuffer createBuffer (GPUBufferDescriptor descriptor );GPUTexture createTexture (GPUTextureDescriptor descriptor );GPUSampler createSampler (optional GPUSamplerDescriptor descriptor = {});GPUExternalTexture importExternalTexture (GPUExternalTextureDescriptor descriptor );GPUBindGroupLayout createBindGroupLayout (GPUBindGroupLayoutDescriptor descriptor );GPUPipelineLayout createPipelineLayout (GPUPipelineLayoutDescriptor descriptor );GPUBindGroup createBindGroup (GPUBindGroupDescriptor descriptor );GPUShaderModule createShaderModule (GPUShaderModuleDescriptor descriptor );GPUComputePipeline createComputePipeline (GPUComputePipelineDescriptor descriptor );GPURenderPipeline createRenderPipeline (GPURenderPipelineDescriptor descriptor );Promise <GPUComputePipeline >createComputePipelineAsync (GPUComputePipelineDescriptor descriptor );Promise <GPURenderPipeline >createRenderPipelineAsync (GPURenderPipelineDescriptor descriptor );GPUCommandEncoder createCommandEncoder (optional GPUCommandEncoderDescriptor descriptor = {});GPURenderBundleEncoder createRenderBundleEncoder (GPURenderBundleEncoderDescriptor descriptor );GPUQuerySet createQuerySet (GPUQuerySetDescriptor descriptor ); };GPUDevice includes GPUObjectBase ;
features, 型 GPUSupportedFeatures, 読み取り専用-
このデバイスがサポートする
GPUFeatureName値のセット([[device]].[[features]])。 limits, 型 GPUSupportedLimits, 読み取り専用-
このデバイスがサポートする制限値(
[[device]].[[limits]])。 queue, 型 GPUQueue, 読み取り専用-
このデバイスの主キュー
GPUQueue。 adapterInfo, 型 GPUAdapterInfo, 読み取り専用-
この
GPUDeviceを生成した物理アダプターの情報。同じ
GPUDeviceに対しては、GPUAdapterInfoの値は常に一定です。毎回同じオブジェクトが返されます。初回生成方法:
呼び出し元:GPUDevicethis.戻り値:
GPUAdapterInfoコンテンツタイムライン手順:
-
this.
[[device]].[[adapter]]に対して新しいアダプター情報を返す。
-
[[device]]
はGPUDeviceが参照するdeviceです。
GPUDeviceは以下のメソッドを持ちます:
destroy()-
デバイスを破棄し、以降の操作を禁止します。 未完了の非同期操作は失敗します。
注意: デバイスは何度破棄しても有効です。
-
Lose the device(this.
[[device]],"destroyed").
注意: このデバイスに対して以降の操作が一切キューされないため、実装は未完了の非同期操作やリソース割り当て(アンマップ直後のメモリ含む)を即座に中断・解放できます。
-
GPUDeviceの許可バッファ用途:
GPUDeviceの許可テクスチャ用途:
4.5. 例
GPUAdapter
およびGPUDevice要求のエラーハンドリング例:
let gpuDevice= null ; async function initializeWebGPU() { // ユーザーエージェントがWebGPUをサポートしているか確認 if ( ! ( 'gpu' in navigator)) { console. error( "ユーザーエージェントがWebGPUをサポートしていません。" ); return false ; } // アダプター要求 const gpuAdapter= await navigator. gpu. requestAdapter(); // 適切なアダプターが見つからない場合、requestAdapterはnullで解決されることがある if ( ! gpuAdapter) { console. error( 'WebGPUアダプターが見つかりません。' ); return false ; } // デバイス要求 // オプション辞書に無効な値が渡された場合、promiseはrejectされる。 // 必ずアダプターのfeaturesやlimitsを事前に確認してからrequestDevice()を呼ぶこと。 gpuDevice= await gpuAdapter. requestDevice(); // requestDeviceはnullを返さないが、何らかの理由で有効なデバイス要求が満たせない場合 // 既に失われたデバイスとしてresolveされることがあり得る。 // また、デバイスは作成後も様々な理由(ブラウザのリソース管理、ドライバ更新等)で // いつでも失われる可能性があるため、常にロストデバイスを適切に扱うこと。 gpuDevice. lost. then(( info) => { console. error( `WebGPUデバイスが失われました: ${ info. message} ` ); gpuDevice= null ; // デバイスロストの多くは一時的なものなので、アプリケーションは // 以前のデバイスが失われたら新規取得を試みるべき(意図的なdestroy理由以外)。 // 前のデバイスで作成したWebGPUリソース(バッファ、テクスチャ等)は // 新しいデバイスで再作成する必要がある。 if ( info. reason!= 'destroyed' ) { initializeWebGPU(); } }); onWebGPUInitialized(); return true ; } function onWebGPUInitialized() { // ここからWebGPUリソース作成処理を開始 } initializeWebGPU();
5. バッファ
5.1. GPUBuffer
GPUBuffer
はGPU操作で利用できるメモリブロックを表します。
データは線形レイアウトで格納されており、割り当て領域の各バイトは
GPUBufferの先頭からのオフセットで参照可能ですが、
操作ごとにアライメント制約があります。一部のGPUBufferは
マップ可能であり、対応するメモリブロックはArrayBuffer
(マッピング)経由でアクセスできます。
GPUBufferは
createBuffer()で作成します。
バッファはmappedAtCreationを指定可能です。
[Exposed =(Window ,Worker ),SecureContext ]interface GPUBuffer {readonly attribute GPUSize64Out size ;readonly attribute GPUFlagsConstant usage ;readonly attribute GPUBufferMapState mapState ;Promise <undefined >mapAsync (GPUMapModeFlags mode ,optional GPUSize64 offset = 0,optional GPUSize64 size );ArrayBuffer getMappedRange (optional GPUSize64 offset = 0,optional GPUSize64 size );undefined unmap ();undefined destroy (); };GPUBuffer includes GPUObjectBase ;enum GPUBufferMapState {"unmapped" ,"pending" ,"mapped" , };
size, 型 GPUSize64Out, 読み取り専用-
GPUBufferの割り当てサイズ(バイト単位)。 usage, 型 GPUFlagsConstant, 読み取り専用-
この
GPUBufferで許可されている用途。
GPUBufferは
以下のコンテンツタイムラインプロパティを持ちます:
mapState, 型 GPUBufferMapState, 読み取り専用-
バッファの現在の
GPUBufferMapState:"unmapped"-
バッファが
this.getMappedRange()で利用できるようにマップされていません。 "pending"-
バッファのマッピング要求が保留中です。
mapAsync()で検証失敗または成功する可能性があります。 "mapped"-
バッファがマップされており、
this.getMappedRange()が利用できます。
コンテンツタイムライン手順:-
this.
[[mapping]]がnullでなければ、"mapped"を返す。 -
this.
[[pending_map]]がnullでなければ、"pending"を返す。 -
"unmapped"を返す。
[[pending_map]], 型Promise<void> またはnull(初期値null)-
現在保留中の
Promise(mapAsync()呼び出し)を返します。保留中のマップは常に1つしかありません。既に要求中の場合、
mapAsync()は即座に拒否します。 [[mapping]], 型 active buffer mapping またはnull(初期値null)-
バッファが現在
getMappedRange()で利用可能な場合のみ設定されます。 それ以外の場合はnullです([[pending_map]]があっても)。active buffer mappingは以下のフィールドを持つ構造体です:
- data, 型 Data Block
-
この
GPUBufferのマッピングデータ。 このデータはArrayBufferビューを通じてアクセスされ、getMappedRange()で返され、viewsに格納されます。 - mode, 型
GPUMapModeFlags -
対応する
mapAsync()またはcreateBuffer()呼び出しで指定されたGPUMapModeFlags。 - range, 型 タプル [
unsigned long long,unsigned long long] -
マップされた
GPUBufferの範囲。 - views, 型 list<
ArrayBuffer> -
アプリケーションに
ArrayBufferとして返されたビュー。unmap()呼び出し時に切り離すため管理されます。
active buffer mappingを初期化するには、 mode modeとrange rangeで以下のコンテンツタイムライン手順を実行:-
sizeをrange[1] - range[0]とする。
-
dataを? CreateByteDataBlock(size)で作成。
注意:この操作はRangeErrorを投げることがあります。 一貫性・予測可能性のため:-
その時点で
new ArrayBuffer()が成功するサイズは、この割り当ても成功すべき。 -
その時点で
new ArrayBuffer()がRangeErrorを 決定的に投げるサイズは、この割り当ても同様にすべき。
-
-
以下を持つactive buffer mappingを返す:
GPUBufferは
以下のデバイスタイムラインプロパティを持ちます:
[[internal state]]-
バッファの現在の内部状態:
- "available"
-
(無効化されていなければ)キュー操作に利用可能。
- "unavailable"
-
マップされているためキュー操作には利用不可。
- "destroyed"
-
destroy()されたため、いかなる操作にも利用不可。
5.1.1. GPUBufferDescriptor
dictionary GPUBufferDescriptor :GPUObjectDescriptorBase {required GPUSize64 size ;required GPUBufferUsageFlags usage ;boolean mappedAtCreation =false ; };
GPUBufferDescriptor
には以下のメンバーがあります:
size, 型 GPUSize64-
バッファのサイズ(バイト単位)。
usage, 型 GPUBufferUsageFlags-
バッファで許可される用途。
mappedAtCreation, 型 boolean(デフォルトfalse)-
trueの場合、バッファは作成時にすでにマップされた状態となり、getMappedRange()が即座に呼び出し可能となります。mappedAtCreationをtrueにしても、usageにMAP_READやMAP_WRITEを含めなくても有効です。 これはバッファの初期データを設定するために利用できます。バッファ作成が最終的に失敗した場合でも、アンマップされるまではマップ範囲に書き込み/読み出しできるように見えることが保証されます。
5.1.2. バッファ用途
typedef [EnforceRange ]unsigned long ; [GPUBufferUsageFlags Exposed =(Window ,Worker ),SecureContext ]namespace {GPUBufferUsage const GPUFlagsConstant MAP_READ = 0x0001;const GPUFlagsConstant MAP_WRITE = 0x0002;const GPUFlagsConstant COPY_SRC = 0x0004;const GPUFlagsConstant COPY_DST = 0x0008;const GPUFlagsConstant INDEX = 0x0010;const GPUFlagsConstant VERTEX = 0x0020;const GPUFlagsConstant UNIFORM = 0x0040;const GPUFlagsConstant STORAGE = 0x0080;const GPUFlagsConstant INDIRECT = 0x0100;const GPUFlagsConstant QUERY_RESOLVE = 0x0200; };
GPUBufferUsage
フラグはGPUBufferが作成後にどのように利用できるかを決定します:
MAP_READ-
バッファは読み出し用にマップ可能です。(例:
mapAsync()でGPUMapMode.READを指定)COPY_DSTとだけ組み合わせ可能です。 MAP_WRITE-
バッファは書き込み用にマップ可能です。(例:
mapAsync()でGPUMapMode.WRITEを指定)COPY_SRCとだけ組み合わせ可能です。 COPY_SRC-
バッファはコピー操作のソースとして利用可能です。(例:copyBufferToBuffer()や
copyBufferToTexture()呼び出しのsource引数) COPY_DST-
バッファはコピーや書き込み操作の宛先として利用可能です。(例:copyBufferToBuffer()や
copyTextureToBuffer()呼び出しのdestination引数、あるいはwriteBuffer()ターゲット) INDEX-
バッファはインデックスバッファとして利用可能です。(例:
setIndexBuffer()への渡し) VERTEX-
バッファは頂点バッファとして利用可能です。(例:
setVertexBuffer()への渡し) UNIFORM-
バッファはユニフォームバッファとして利用可能です。(例:
GPUBufferBindingLayoutのバインドグループエントリでbuffer.typeが"uniform"の場合) STORAGE-
バッファはストレージバッファとして利用可能です。(例:
GPUBufferBindingLayoutのバインドグループエントリでbuffer.typeが"storage"または"read-only-storage"の場合) INDIRECT-
バッファは間接コマンド引数の保存に利用可能です。(例:
indirectBuffer引数としてdrawIndirect()やdispatchWorkgroupsIndirect()呼び出しで利用) QUERY_RESOLVE-
バッファはクエリ結果の取得に利用可能です。(例:
destination引数としてresolveQuerySet()呼び出しで使用)
5.1.3. バッファ作成
createBuffer(descriptor)-
GPUBufferを作成します。呼び出し元:GPUDevicethis.引数:
GPUDevice.createBuffer(descriptor)メソッドの引数。 パラメータ 型 Nullable Optional 説明 descriptorGPUBufferDescriptor✘ ✘ 作成する GPUBufferの記述。戻り値:
GPUBufferコンテンツタイムライン手順:
-
bを!新しいWebGPUオブジェクトの作成(this,
GPUBuffer, descriptor)とする。 -
もしdescriptor.
mappedAtCreationがtrueなら:-
descriptor.
sizeが4の倍数でない場合、RangeErrorを投げる。 -
b.
[[mapping]]に ?active buffer mappingの初期化 (modeWRITE, range[0, descriptor.) を設定する。size]
-
-
initialization stepsをthisのデバイスタイムラインで発行する。
-
bを返す。
デバイスタイムライン initialization steps:-
以下の要件が満たされない場合、 検証エラー生成、無効化 b、return。
-
thisは失われていてはならない。
-
descriptor.
usageは0であってはならない。 -
descriptor.
sizeは this.[[device]].[[limits]].maxBufferSize以下でなければならない。
-
注意: バッファ作成が失敗し、descriptor.
mappedAtCreationがfalseの場合、mapAsync()呼び出しは拒否されるため、マッピング用に割り当てられたリソースは破棄または再利用される可能性があります。-
もしdescriptor.
mappedAtCreationがtrueなら:-
b.
[[internal state]]を"unavailable"に設定する。
それ以外:
-
b.
[[internal state]]を"available"に設定する。
-
-
bのデバイス割り当てを各バイト0で作成する。
-
const buffer= gpuDevice. createBuffer({ size: 128 , usage: GPUBufferUsage. UNIFORM| GPUBufferUsage. COPY_DST});
5.1.4. バッファ破棄
アプリケーションがGPUBufferを不要と判断した場合、destroy()を呼び出すことでガベージコレクション前にアクセスを失うことができます。バッファの破棄はマッピングも解除し、マッピング用に割り当てられたメモリも解放します。
注意: これにより、ユーザーエージェントは、そのバッファを使ったすべての操作が完了した時点でGPUメモリを回収できます。
GPUBufferは以下のメソッドを持ちます:
destroy()-
GPUBufferを破棄します。注意: バッファは何度破棄しても有効です。
呼び出し元:GPUBufferthis.戻り値:
undefinedコンテンツタイムライン手順:
-
this.
unmap()を呼び出す。 -
以降の手順をthis.
[[device]]のデバイスタイムラインで発行する。
デバイスタイムライン手順:-
this.
[[internal state]]を "destroyed"に設定する。
注意: このバッファを使った以降の操作は一切キューできなくなるため、実装はリソース割り当て(アンマップ直後のメモリも含む)を即座に解放可能です。
-
5.2. バッファのマッピング
アプリケーションはGPUBufferをマッピングするよう要求でき、これによりArrayBufferでGPUBufferの一部割り当て領域にアクセス可能となります。GPUBufferのマッピング要求はmapAsync()で非同期に行われ、ユーザーエージェントがGPUの利用完了を確認してからアプリケーションが内容にアクセスできるようにします。マップ中のGPUBufferはGPUで利用できず、unmap()でアンマップしないと、Queueタイムラインで作業登録できません。
一度GPUBufferがマップされると、アプリケーションはgetMappedRange()で範囲アクセスを同期的に要求できます。返されたArrayBufferはunmap()(直接またはGPUBuffer.destroy()やGPUDevice.destroy()経由)でのみdetach可能です。transferはできません。他の操作がそれを試みるとTypeErrorが投げられます。
typedef [EnforceRange ]unsigned long ; [GPUMapModeFlags Exposed =(Window ,Worker ),SecureContext ]namespace {GPUMapMode const GPUFlagsConstant READ = 0x0001;const GPUFlagsConstant WRITE = 0x0002; };
GPUMapMode
フラグはGPUBufferがmapAsync()でどのようにマップされるかを決定します:
READ-
このフラグは
MAP_READ用途で作成されたバッファにのみ有効です。バッファがマップされると、
getMappedRange()呼び出しはバッファの現行値を含むArrayBufferを返します。返されたArrayBufferの変更はunmap()呼び出し後に破棄されます。 WRITE-
このフラグは
MAP_WRITE用途で作成されたバッファにのみ有効です。バッファがマップされると、
getMappedRange()呼び出しはバッファの現行値を含むArrayBufferを返します。返されたArrayBufferの変更はGPUBufferにunmap()呼び出し後に保存されます。注意:
MAP_WRITE用途のバッファはCOPY_SRC用途のみと組み合わせ可能なため、書き込み用マッピングではGPUで生成された値は返されません。返されるArrayBufferはデフォルト初期化(ゼロ)または前回マッピング時にウェブページで書き込まれたデータのみを含みます。
GPUBufferは以下のメソッドを持ちます:
mapAsync(mode, offset, size)-
指定された範囲の
GPUBufferをマップし、Promiseが解決されるとGPUBufferの内容をgetMappedRange()でアクセスできるようになります。返された
Promiseの解決はマップが完了したことのみを示し、 現行標準タイムライン上で見える他の操作の完了は保証しません。 特に、他のPromise(onSubmittedWorkDone()や他のmapAsync())が解決されていることは意味しません。Promise(onSubmittedWorkDone())の解決は、 その呼び出し前に同じキューで排他的に使われたGPUBufferのmapAsync()が完了していることを意味します。呼び出し元:GPUBufferthis.引数:
GPUBuffer.mapAsync(mode, offset, size)メソッドの引数。 パラメータ 型 Nullable Optional 説明 modeGPUMapModeFlags✘ ✘ バッファを読み取り/書き込みどちらでマップするか。 offsetGPUSize64✘ ✔ マップ範囲の開始バイトオフセット。 sizeGPUSize64✘ ✔ マップする範囲のバイト数。 コンテンツタイムライン手順:
-
contentTimelineを現在のコンテンツタイムラインとする。
-
this.
mapStateが"unmapped"でない場合:-
this.
[[device]]のデバイスタイムラインでearly-reject stepsを発行する。
-
-
pを新しい
Promiseとする。 -
this.
[[pending_map]]にpを設定する。 -
this.
[[device]]のデバイスタイムラインでvalidation stepsを発行する。 -
pを返す。
デバイスタイムライン early-reject steps:-
Return。
デバイスタイムライン validation steps:-
sizeが
undefinedの場合:-
rangeSizeにmax(0, this.
size- offset)を設定。
それ以外の場合:
-
rangeSizeにsizeを設定。
-
-
以下の条件が満たされない場合:
-
thisは有効でなければならない。
-
deviceLostを
trueに設定。 -
contentTimelineでmap failure stepsを発行。
-
Return。
-
-
以下の条件が満たされない場合:
それ以外の場合:
-
deviceLostを
falseに設定。 -
contentTimelineでmap failure stepsを発行。
-
Return。
-
-
this.
[[internal state]]を"unavailable"に設定。注: バッファがマップされている間は、
unmap()まで内容は変更されません。 -
次のいずれかのイベントが発生した時点(先に発生した方、またはすでに発生していれば):
-
デバイスタイムラインが未特定のキュータイムラインの完了を認識:
-
現在キュー済みのthis利用操作の完了後
-
現在キュー済みの全操作の完了までに(thisの利用有無に関わらず)
-
-
this.
[[device]]が失われた場合。
その後、this.
[[device]]のデバイスタイムラインで後続の手順を発行する。 -
デバイスタイムライン手順:-
this.
[[device]]が失われた場合はdeviceLostをtrue、それ以外はfalseに設定。注: デバイス喪失は前ブロックとこの間でも起こり得ます。
-
deviceLostが
trueの場合:-
contentTimelineでmap failure stepsを発行。
それ以外の場合:
-
internalStateAtCompletionをthis.
[[internal state]]とする。注: この時点で
unmap()呼び出しでバッファが再び"available"になった場合、[[pending_map]]はpと異なるため、以下のマッピングは成功しません。 -
dataForMappedRegionにthisのoffsetからrangeSizeバイト分の内容を設定。
-
contentTimelineでmap success stepsを発行。
-
コンテンツタイムライン map success steps:-
this.
[[pending_map]]がpと異なる場合:注:
unmap()によりマップがキャンセルされています。-
Assert pは拒否されている。
-
Return。
-
-
Assert pはpendingである。
-
Assert internalStateAtCompletionは"unavailable"。
-
mappingをactive buffer mappingの初期化 (mode mode, range
[offset, offset + rangeSize])で生成する。この割り当てに失敗した場合:
-
this.
[[pending_map]]をnullにし、RangeErrorでpを拒否。 -
Return。
-
-
mapping.dataの内容をdataForMappedRegionに設定する。
-
this.
[[mapping]]にmappingを設定する。 -
this.
[[pending_map]]をnullにし、pをresolveする。
コンテンツタイムライン map failure steps:-
this.
[[pending_map]]がpと異なる場合:注:
unmap()によりマップがキャンセルされています。-
Assert pはすでに拒否されている。
-
Return。
-
-
Assert pはまだpendingである。
-
this.
[[pending_map]]をnullに設定する。 -
deviceLostがtrueの場合:
-
注:
unmap()でキャンセルされた場合も同じエラータイプです。
それ以外の場合:
-
-
getMappedRange(offset, size)-
指定したマップ範囲の
ArrayBufferを返します。内容はGPUBufferのものです。呼び出し元:GPUBufferthis.引数:
GPUBuffer.getMappedRange(offset, size)メソッドの引数。 パラメータ 型 Nullable Optional 説明 offsetGPUSize64✘ ✔ バッファ内容取得開始のバイトオフセット。 sizeGPUSize64✘ ✔ 返す ArrayBufferのバイトサイズ。戻り値:
ArrayBufferコンテンツタイムライン手順:
-
sizeが指定されていなければ:
-
rangeSizeをmax(0, this.
size- offset)とする。
指定されていればrangeSizeはsize。
-
-
以下の条件が満たされない場合、
OperationErrorを投げて終了:-
this.
[[mapping]]がnullでない。 -
offsetは8の倍数。
-
rangeSizeは4の倍数。
-
offset ≥ this.
[[mapping]].range[0]。 -
offset + rangeSize ≤ this.
[[mapping]].range[1]。 -
[offset, offset + rangeSize)がthis.
[[mapping]].viewsの他範囲と重複しない。
注:
GPUBufferがmappedAtCreationの場合、無効でも常にgetMappedRangeは有効です。現行標準タイムラインが無効性を認識できないためです。 -
-
dataをthis.
[[mapping]].dataとする。 -
viewを! ArrayBufferの生成(サイズrangeSize、ポインタはdataの(offset -
[[mapping]].range[0])バイト先を参照)とする。注: dataは
mapAsync()やcreateBuffer()ですでに割り当てられているため、ここでRangeErrorは投げられません。 -
view.
[[ArrayBufferDetachKey]]に"WebGPUBufferMapping"を設定する。注:
TypeErrorは、unmap()以外でDetachArrayBufferしようとした場合に投げられる。 -
viewをthis.
[[mapping]].viewsに追加する。 -
viewを返す。
注:
getMappedRange()でmapの状態確認なしに成功した場合、ユーザーエージェントは開発者向け警告を表示検討すべきです。mapAsync()の成功、mapStateが"mapped"、または後のonSubmittedWorkDone()成功を待つことで状態確認できる。 -
unmap()-
マップされた範囲のアンマップを行い、内容をGPUで再び利用可能にします。
呼び出し元:GPUBufferthis.戻り値:
undefinedコンテンツタイムライン手順:
-
this.
[[pending_map]]がnullでない場合:-
this.
[[pending_map]]をAbortErrorで拒否する。 -
this.
[[pending_map]]をnullに設定
-
-
this.
[[mapping]]がnullの場合:-
Return。
-
-
各
ArrayBufferabについて、this.[[mapping]].views内:-
DetachArrayBuffer(ab,"WebGPUBufferMapping")を実行
-
-
bufferUpdateを
nullとする。 -
this.
[[mapping]].modeがWRITEを含む場合:-
bufferUpdate = {
data: this.[[mapping]].data,offset: this.[[mapping]].range[0] }とする。
注:
WRITEモードでない場合、アンマップ時にアプリケーションによるローカル変更は破棄され、後のマッピング内容には影響しない。 -
-
this.
[[mapping]]をnullに設定 -
以降の手順をthis.
[[device]]のデバイスタイムラインで発行
デバイスタイムライン手順:-
以下の条件が満たされない場合はreturn:
-
thisはthis.
[[device]]で有効に利用可能である必要がある。
-
-
Assert this.
[[internal state]]は"unavailable"。 -
bufferUpdateが
nullでなければ:-
this.
[[device]].queueのキュータイムラインで以下発行:キュータイムライン手順:-
thisのbufferUpdate.
offsetからbufferUpdate.dataで内容更新
-
-
-
this.
[[internal state]]を"available"に設定
-
6. テクスチャとテクスチャビュー
6.1. GPUTexture
テクスチャは、1d・
2d・
3d
のデータ配列で構成され、各要素が複数の値を持つことで色などを表現できます。テクスチャは、作成時のGPUTextureUsage
に応じて様々な方法で読み書きが可能です。例えば、レンダー/コンピュートパイプラインのシェーダからサンプリング・読み書きでき、レンダーパスの出力として書き込むこともできます。
内部的には、テクスチャは線形アクセスではなく多次元アクセスに最適化されたGPUメモリレイアウトで格納されていることが多いです。
1つのテクスチャは、1つ以上のテクスチャサブリソースから構成されます。
各サブリソースはミップマップレベルで一意に識別され、
2dテクスチャの場合のみ、配列レイヤー
およびアスペクトでも識別されます。
テクスチャサブリソースはサブリソースであり、それぞれが1つの利用スコープ内で異なる内部用途に利用できます。
ミップマップレベル内の各サブリソースは、
1つ下のレベルのリソースと比べて各空間次元で約半分のサイズです
(論理ミップレベル別テクスチャ範囲参照)。
レベル0のサブリソースがテクスチャ本体の寸法となります。
より小さいレベルは通常、同じ画像の低解像度版の格納に用いられます。
GPUSamplerやWGSLは、
詳細度レベルの選択や補間を明示的または自動で行う仕組みを提供します。
"2d"
テクスチャは配列レイヤーの配列になる場合があります。
各レイヤー内のサブリソースは他レイヤーの同じリソースと同サイズです。
2d以外のテクスチャでは全てのサブリソースの配列レイヤーインデックスは0です。
各サブリソースはアスペクトを持ちます。
カラーテクスチャはcolorのみです。
深度・ステンシルフォーマットのテクスチャは複数アスペクト(depth・
stencil)を持つ場合があり、
depthStencilAttachmentや
"depth"バインディングなどで特殊な用途に使われます。
"3d"
テクスチャは複数のスライス(各z値ごとの2次元画像)を持ちます。
スライスはサブリソースとは異なります。
[Exposed =(Window ,Worker ),SecureContext ]interface GPUTexture {GPUTextureView createView (optional GPUTextureViewDescriptor descriptor = {});undefined destroy ();readonly attribute GPUIntegerCoordinateOut width ;readonly attribute GPUIntegerCoordinateOut height ;readonly attribute GPUIntegerCoordinateOut depthOrArrayLayers ;readonly attribute GPUIntegerCoordinateOut mipLevelCount ;readonly attribute GPUSize32Out sampleCount ;readonly attribute GPUTextureDimension dimension ;readonly attribute GPUTextureFormat format ;readonly attribute GPUFlagsConstant usage ; };GPUTexture includes GPUObjectBase ;
GPUTexture
には以下の不変プロパティがあります:
width, 型 GPUIntegerCoordinateOut, 読み取り専用-
この
GPUTextureの幅。 height, 型 GPUIntegerCoordinateOut, 読み取り専用-
この
GPUTextureの高さ。 depthOrArrayLayers, 型 GPUIntegerCoordinateOut, 読み取り専用-
この
GPUTextureの深度またはレイヤー数。 mipLevelCount, 型 GPUIntegerCoordinateOut, 読み取り専用-
この
GPUTextureのミップレベル数。 sampleCount, 型 GPUSize32Out, 読み取り専用-
この
GPUTextureのサンプル数。 dimension, 型 GPUTextureDimension, 読み取り専用-
各
GPUTextureサブリソースごとのテクセルの次元。 format, 型 GPUTextureFormat, 読み取り専用-
この
GPUTextureのフォーマット。 usage, 型 GPUFlagsConstant, 読み取り専用-
この
GPUTextureで許可される用途。 [[viewFormats]], 型 sequence<GPUTextureFormat>-
この
GPUTextureに対してGPUTextureViewDescriptor.formatとして利用可能なGPUTextureFormatの集合。
GPUTexture
には以下のデバイスタイムラインプロパティがあります:
[[destroyed]], 型boolean, 初期値false-
テクスチャが破棄された場合、いかなる操作にも利用できなくなり、基盤となるメモリも解放可能となります。
引数:
-
GPUExtent3DbaseSize -
GPUSize32mipLevel
戻り値: GPUExtent3DDict
デバイスタイムライン手順:
-
extentを新しい
GPUExtent3DDictオブジェクトとする。 -
extent.
depthOrArrayLayersに1を設定。 -
extentを返す。
論理ミップレベル別テクスチャ範囲とは、特定のミップレベルにおけるテクスチャのテクセル単位のサイズです。次の手順で算出されます:
引数:
-
GPUTextureDescriptordescriptor -
GPUSize32mipLevel
戻り値: GPUExtent3DDict
-
extentを新しい
GPUExtent3DDictオブジェクトとする。 -
descriptor.
dimensionが次の場合:"1d"-
-
extent.
heightに1を設定。 -
extent.
depthOrArrayLayersに1を設定。
"2d"-
-
extent.
heightにmax(1, descriptor.size.height ≫ mipLevel)を設定。 -
extent.
depthOrArrayLayersにdescriptor.size.depthOrArrayLayersを設定。
"3d"-
-
extent.
heightにmax(1, descriptor.size.height ≫ mipLevel)を設定。 -
extent.
depthOrArrayLayersにmax(1, descriptor.size.depthOrArrayLayers ≫ mipLevel)を設定。
-
extentを返す。
物理ミップレベル別テクスチャ範囲とは、特定のミップレベルにおけるテクスチャのテクセル単位のサイズ(テクセルブロックを完全に構成するための余分なパディングを含む)です。次の手順で算出されます:
引数:
-
GPUTextureDescriptordescriptor -
GPUSize32mipLevel
戻り値: GPUExtent3DDict
-
extentを新しい
GPUExtent3DDictオブジェクトとする。 -
logicalExtentに論理ミップレベル別テクスチャ範囲(descriptor, mipLevel)を設定。
-
descriptor.
dimensionが次の場合:"1d"-
-
extent.
widthにlogicalExtent.widthをdescriptorのテクセルブロック幅の倍数に切り上げて設定。 -
extent.
heightに1を設定。 -
extent.
depthOrArrayLayersに1を設定。
-
"2d"-
-
extent.
widthにlogicalExtent.widthをdescriptorのテクセルブロック幅の倍数に切り上げて設定。 -
extent.
heightにlogicalExtent.heightをdescriptorのテクセルブロック高さの倍数に切り上げて設定。 -
extent.
depthOrArrayLayersにlogicalExtent.depthOrArrayLayersを設定。
-
"3d"-
-
extent.
widthにlogicalExtent.widthをdescriptorのテクセルブロック幅の倍数に切り上げて設定。 -
extent.
heightにlogicalExtent.heightをdescriptorのテクセルブロック高さの倍数に切り上げて設定。 -
extent.
depthOrArrayLayersにlogicalExtent.depthOrArrayLayersを設定。
-
-
extentを返す。
6.1.1. GPUTextureDescriptor
dictionary GPUTextureDescriptor :GPUObjectDescriptorBase {required GPUExtent3D size ;GPUIntegerCoordinate mipLevelCount = 1;GPUSize32 sampleCount = 1;GPUTextureDimension dimension = "2d";required GPUTextureFormat format ;required GPUTextureUsageFlags usage ;sequence <GPUTextureFormat >viewFormats = []; };
GPUTextureDescriptor
には以下のメンバーがあります:
size, 型 GPUExtent3D-
テクスチャの幅・高さ・深度またはレイヤー数。
mipLevelCount, 型 GPUIntegerCoordinate(デフォルト値1)-
このテクスチャが持つミップレベルの数。
sampleCount, 型 GPUSize32(デフォルト値1)-
テクスチャのサンプル数。
sampleCount>1の場合はマルチサンプルテクスチャ。 dimension, 型 GPUTextureDimension(デフォルト値"2d")-
テクスチャが一次元か、二次元レイヤー配列か、三次元か。
format, 型 GPUTextureFormat-
テクスチャのフォーマット。
usage, 型 GPUTextureUsageFlags-
テクスチャの許可用途。
viewFormats, 型 sequence<GPUTextureFormat>(デフォルト値[])-
このテクスチャで
formatとしてcreateView()を呼び出す際に許可される値(実際のformatを含む)。注:このリストにフォーマットを追加するとパフォーマンスに大きな影響が出る可能性があるため、不要な追加は避けてください。実際の影響はシステム依存ですので、アプリケーションごとに様々なシステムで検証が必要です。 例えば、あるシステムでは
formatやviewFormatsに"rgba8unorm-srgb"を入れると、"rgba8unorm"のテクスチャより最適でなくなる場合があります。他フォーマットや組み合わせでも同様の注意点があります。このリストのフォーマットは、テクスチャのフォーマットとテクスチャビュー・フォーマット互換でなければなりません。
2つのGPUTextureFormatformatとviewFormatは、以下の場合テクスチャビュー・フォーマット互換です:-
formatとviewFormatが等しい場合
-
formatとviewFormatが
srgb(-srgbサフィックス)だけが異なる場合
-
enum {GPUTextureDimension "1d" ,"2d" ,"3d" , };
"1d"-
一次元(幅のみ)のテクスチャ。
"1d"テクスチャはミップマップ不可・マルチサンプル不可・圧縮/深度/ステンシル不可・レンダーターゲット不可です。 "2d"-
幅・高さを持ち、レイヤーも持てるテクスチャ。
"3d"-
幅・高さ・深度を持つテクスチャ。
"3d"テクスチャはマルチサンプル不可・フォーマットは3d対応(プレーンカラーフォーマットや一部パック/圧縮フォーマット)のみ。
6.1.2. テクスチャ用途
typedef [EnforceRange ]unsigned long ; [GPUTextureUsageFlags Exposed =(Window ,Worker ),SecureContext ]namespace {GPUTextureUsage const GPUFlagsConstant COPY_SRC = 0x01;const GPUFlagsConstant COPY_DST = 0x02;const GPUFlagsConstant TEXTURE_BINDING = 0x04;const GPUFlagsConstant STORAGE_BINDING = 0x08;const GPUFlagsConstant RENDER_ATTACHMENT = 0x10; };
GPUTextureUsage
のフラグは、GPUTexture
の作成後の用途を決定します:
COPY_SRC-
コピー操作のソースとして利用可能(例:
source引数としてcopyTextureToTexture()やcopyTextureToBuffer())。 COPY_DST-
コピー・書き込み操作のデスティネーションとして利用可能(例:
destination引数としてcopyTextureToTexture()やcopyBufferToTexture()、writeTexture()のターゲット)。 TEXTURE_BINDING-
シェーダでサンプル用テクスチャとしてバインド可能(例:
GPUTextureBindingLayoutのバインドグループエントリ)。 STORAGE_BINDING-
シェーダでストレージテクスチャとしてバインド可能(例:
GPUStorageTextureBindingLayoutのバインドグループエントリ)。 RENDER_ATTACHMENT-
レンダーパスのカラー/深度・ステンシルアタッチメントとして利用可能(例:
GPURenderPassColorAttachment.viewやGPURenderPassDepthStencilAttachment.view)。
引数:
-
GPUTextureDimensiondimension -
GPUTextureDimensionsize
6.1.3. テクスチャの作成
createTexture(descriptor)-
GPUTextureを作成します。呼び出し元:GPUDevicethis.引数:
GPUDevice.createTexture(descriptor)メソッドの引数。 パラメータ 型 Nullable Optional 説明 descriptorGPUTextureDescriptor✘ ✘ 作成する GPUTextureの説明。戻り値:
GPUTextureコンテンツタイムライン手順:
-
? GPUExtent3D形状の検証(descriptor.
size)。 -
? テクスチャフォーマット必要機能の検証( descriptor.
format、this.[[device]])。 -
? 各viewFormats要素のテクスチャフォーマット必要機能の検証( descriptor.
viewFormats、 this.[[device]])。 -
tを! 新しいWebGPUオブジェクトの生成(this,
GPUTexture, descriptor)とする。 -
t.
depthOrArrayLayersにdescriptor.size.depthOrArrayLayersを設定。 -
t.
mipLevelCountにdescriptor.mipLevelCountを設定。 -
t.
sampleCountにdescriptor.sampleCountを設定。 -
thisのデバイスタイムラインでinitialization stepsを発行。
-
tを返す。
デバイスタイムライン initialization steps:-
以下の条件が満たされない場合検証エラーの生成、tの無効化、return。
-
GPUTextureDescriptorの検証(this, descriptor) が
trueを返す。
-
-
t.
[[viewFormats]]にdescriptor.viewFormatsを設定。 -
各ブロックがゼロのビット表現と等価な等価テクセル表現になるよう、tのデバイス割り当てを作成。
割り当てが副作用なしに失敗した場合、 メモリ不足エラー生成、tの無効化、return。
-
引数:
-
GPUDevicethis -
GPUTextureDescriptordescriptor
デバイスタイムライン手順:
-
limitsをthis.
[[limits]]とする。 -
以下すべて満たせば
true、そうでなければfalseを返す:-
thisが失われていないこと。
-
descriptor.
usageは0でないこと。 -
descriptor.
usageはthisの許可されたテクスチャ用途ビットのみを含むこと。 -
descriptor.
size.width, descriptor.size.height, descriptor.size.depthOrArrayLayersがゼロ超であること。 -
descriptor.
mipLevelCountがゼロ超であること。 -
descriptor.
sampleCountが1または4であること。 -
descriptor.
dimensionが:"1d"-
-
descriptor.
size.widthがlimits.maxTextureDimension1D以下。 -
descriptor.
size.depthOrArrayLayers が1。 -
descriptor.
sampleCountが1。 -
descriptor.
formatが圧縮フォーマットまたは深度・ステンシルフォーマットでない。
-
"2d"-
-
descriptor.
size.widthがlimits.maxTextureDimension2D以下。 -
descriptor.
size.heightがlimits.maxTextureDimension2D以下。 -
descriptor.
size.depthOrArrayLayers がlimits.maxTextureArrayLayers以下。
-
"3d"-
-
descriptor.
size.widthがlimits.maxTextureDimension3D以下。 -
descriptor.
size.heightがlimits.maxTextureDimension3D以下。 -
descriptor.
size.depthOrArrayLayers がlimits.maxTextureDimension3D以下。 -
descriptor.
sampleCountが1。 -
descriptor.
formatが§ 26.1 テクスチャフォーマットの機能で3dテクスチャ対応。
-
-
descriptor.
size.heightがテクセルブロック高さの倍数。 -
descriptor.
sampleCount> 1の場合:-
descriptor.
mipLevelCountが1。 -
descriptor.
size.depthOrArrayLayers が1。 -
descriptor.
usageにSTORAGE_BINDINGビット含まない。 -
descriptor.
usageにRENDER_ATTACHMENTビットを含む。 -
descriptor.
formatが§ 26.1 テクスチャフォーマットの機能でマルチサンプリング対応。
-
-
descriptor.
mipLevelCountが 最大ミップレベル数(descriptor.dimension, descriptor.size)以下。 -
descriptor.
usageにRENDER_ATTACHMENTビット含む場合:-
descriptor.
formatがレンダー可能フォーマット。
-
-
descriptor.
usageにSTORAGE_BINDINGビット含む場合:-
descriptor.
formatが§ 26.1.1 プレーンカラーフォーマット表でSTORAGE_BINDING機能を持つアクセスモード少なくとも1つを持つこと。
-
-
各viewFormatについて、descriptor.
viewFormats、 descriptor.formatとviewFormatが テクスチャビュー・フォーマット互換であること。注:viewFormatが指定usageビットと互換でない場合、実装は開発者向け警告を考慮しても良いです。その場合、そのviewFormatは利用不可となります。
-
const texture= gpuDevice. createTexture({ size: { width: 16 , height: 16 }, format: 'rgba8unorm' , usage: GPUTextureUsage. TEXTURE_BINDING, });
6.1.4. テクスチャの破棄
アプリケーションがGPUTexture
を不要になった場合、
ガベージコレクション前にdestroy()を呼び出してアクセスを失わせることができます。
注: これにより、ユーザーエージェントはGPUTexture
に関連付けられたGPUメモリを
それまでに提出されたすべての操作が完了次第、回収できるようになります。
GPUTexture
には次のメソッドがあります:
destroy()-
GPUTextureを破棄します。デバイスタイムライン手順:-
this.
[[destroyed]]をtrueに設定する。
-
6.2. GPUTextureView
GPUTextureView
は、特定のGPUTextureが持つテクスチャサブリソースの部分集合へのビューです。
[Exposed =(Window ,Worker ),SecureContext ]interface GPUTextureView { };GPUTextureView includes GPUObjectBase ;
GPUTextureView
には以下の不変プロパティがあります:
[[texture]], readonly-
このビューが参照する
GPUTexture。 [[descriptor]], readonly-
このテクスチャビューを記述する
GPUTextureViewDescriptor。GPUTextureViewDescriptorのすべてのオプションフィールドが定義済みです。 [[renderExtent]], readonly-
レンダー可能ビューの場合、描画時の有効な
GPUExtent3DDict。注: この範囲は
baseMipLevelに依存します。
[[descriptor]]
descを用いて、
view.[[texture]]
のサブリソースのうち、各サブリソースsが以下を満たすものです:
-
sのミップマップレベルが desc.
baseMipLevel以上、 desc.baseMipLevel+ desc.mipLevelCount未満。 -
sの配列レイヤーが desc.
baseArrayLayer以上、 desc.baseArrayLayer+ desc.arrayLayerCount未満。
2つのGPUTextureView
オブジェクトは、そのサブリソース集合が交差する場合に限りテクスチャビュー・エイリアスとなります。
6.2.1. テクスチャビューの作成
dictionary :GPUTextureViewDescriptor GPUObjectDescriptorBase {GPUTextureFormat format ;GPUTextureViewDimension dimension ;GPUTextureUsageFlags usage = 0;GPUTextureAspect aspect = "all";GPUIntegerCoordinate baseMipLevel = 0;GPUIntegerCoordinate mipLevelCount ;GPUIntegerCoordinate baseArrayLayer = 0;GPUIntegerCoordinate arrayLayerCount ; };
GPUTextureViewDescriptor
には以下のメンバーがあります:
format, 型 GPUTextureFormat-
テクスチャビューのフォーマット。テクスチャ自体の
formatか、 または作成時に指定したviewFormatsのいずれかでなければなりません。 dimension, 型 GPUTextureViewDimension-
テクスチャをどの次元でビューするか。
usage, 型 GPUTextureUsageFlags(デフォルト値0)-
テクスチャビューの許可用途。テクスチャの
usageフラグの部分集合でなければなりません。0の場合、テクスチャの全usageフラグをデフォルトとします。注: ビューの
formatがテクスチャの全usageに対応しない場合、デフォルトは失敗し、明示的にusageを指定する必要があります。 aspect, 型 GPUTextureAspect(デフォルト値"all")-
テクスチャビューからアクセス可能な
aspect。 baseMipLevel, 型 GPUIntegerCoordinate(デフォルト値0)-
テクスチャビューからアクセス可能な最初(最詳細)のミップマップレベル。
mipLevelCount, 型 GPUIntegerCoordinate-
baseMipLevelから始まるミップマップレベル数。 baseArrayLayer, 型 GPUIntegerCoordinate(デフォルト値0)-
テクスチャビューからアクセス可能な最初の配列レイヤーのインデックス。
arrayLayerCount, 型 GPUIntegerCoordinate-
baseArrayLayerから始まるアクセス可能な配列レイヤー数。
enum {GPUTextureViewDimension "1d" ,"2d" ,"2d-array" ,"cube" ,"cube-array" ,"3d" , };
"1d"-
テクスチャを一次元画像としてビューします。
対応WGSL型:
-
texture_1d -
texture_storage_1d
-
"2d"-
テクスチャを単一の二次元画像としてビューします。
対応WGSL型:
-
texture_2d -
texture_storage_2d -
texture_multisampled_2d -
texture_depth_2d -
texture_depth_multisampled_2d
-
"2d-array"-
テクスチャビューを二次元画像の配列としてビューします。
対応WGSL型:
-
texture_2d_array -
texture_storage_2d_array -
texture_depth_2d_array
-
"cube"-
テクスチャをキューブマップとしてビューします。
ビューは6つの配列レイヤーを持ち、それぞれキューブの面(
[+X, -X, +Y, -Y, +Z, -Z])と以下の向きに対応します:キューブマップ面。+U/+V軸は個々の面のテクスチャ座標、すなわち各面のテクセルコピーメモリレイアウトを示します。 注: 内側からビューした場合、+Xが右、+Yが上、+Zが前の左手座標系になります。
サンプリングはキューブマップの面をまたいでシームレスに行われます。
対応WGSL型:
-
texture_cube -
texture_depth_cube
-
"cube-array"-
テクスチャをn個のキューブマップのパック配列としてビューします。それぞれ6配列レイヤーで1つの
"cube"ビューとして扱われ、合計で6n配列レイヤーとなります。対応WGSL型:
-
texture_cube_array -
texture_depth_cube_array
-
"3d"-
テクスチャを三次元画像としてビューします。
対応WGSL型:
-
texture_3d -
texture_storage_3d
-
各GPUTextureAspect値はアスペクトの集合に対応します。
アスペクト集合は以下の各値ごとに定義されています。
enum GPUTextureAspect {"all" ,"stencil-only" ,"depth-only" , };
"all"-
テクスチャフォーマットの利用可能な全アスペクトがテクスチャビューからアクセス可能になります。カラーフォーマットの場合colorアスペクトが、複合深度ステンシルフォーマットの場合はdepthとstencil両方が、単一アスペクトの深度・ステンシルフォーマットはそのアスペクトのみアクセス可能です。
"stencil-only"-
深度・ステンシルフォーマットのstencilアスペクトのみがテクスチャビューからアクセス可能です。
"depth-only"-
深度・ステンシルフォーマットのdepthアスペクトのみがテクスチャビューからアクセス可能です。
createView(descriptor)-
GPUTextureViewを作成します。注:デフォルトではcreateView()は、 テクスチャ全体を表現できる次元でビューを作成します。例えば、createView()を"2d"テクスチャ(レイヤー複数)に対して呼ぶと、"2d-array"GPUTextureViewが作られます(たとえarrayLayerCountが1でも)。レイヤー数が開発時に不明なソース由来テクスチャの場合は、
createView()呼び出し時に明示的なdimensionを指定してシェーダ互換性を確保するのが推奨されます。呼び出し元:GPUTexturethis.引数:
GPUTexture.createView(descriptor)メソッドの引数。 パラメータ 型 Nullable Optional 説明 descriptorGPUTextureViewDescriptor✘ ✔ 作成する GPUTextureViewの説明。戻り値: view(型
GPUTextureView)現行標準タイムライン手順:
-
? テクスチャフォーマット必要機能の検証( descriptor.
format、 this.[[device]])。 -
viewを! 新しいWebGPUオブジェクト生成(this,
GPUTextureView, descriptor)とする。 -
thisのデバイスタイムラインでinitialization stepsを発行。
-
viewを返す。
デバイスタイムライン initialization steps:-
descriptorにGPUTextureViewDescriptor既定値の解決(this, descriptor)の結果を設定。
-
以下の条件が満たされない場合検証エラー生成、viewの無効化、return。
-
thisがthis.
[[device]]で有効利用可能であること。 -
もしdescriptor.
aspectが"all"の場合:-
descriptor.
formatはthis.formatまたはthis.[[viewFormats]]のいずれかに等しいこと。
それ以外の場合:
-
descriptor.
formatがGPUTextureAspectの解決( this.format、 descriptor.aspect)に等しいこと。
-
-
もしdescriptor.
usageにRENDER_ATTACHMENTビットを含む場合:-
descriptor.
formatがレンダー可能フォーマットであること。
-
-
もしdescriptor.
usageにSTORAGE_BINDINGビットを含む場合:-
descriptor.
formatが§ 26.1.1 プレーンカラーフォーマット表でSTORAGE_BINDINGの機能を持つアクセスモード少なくとも1つに含まれること。
-
-
descriptor.
mipLevelCountが0超であること。 -
descriptor.
baseMipLevel+ descriptor.mipLevelCountがthis.mipLevelCount以下。 -
descriptor.
arrayLayerCountが0超であること。 -
descriptor.
baseArrayLayer+ descriptor.arrayLayerCountがthisの配列レイヤー数以下。 -
もしthis.
sampleCount> 1の場合、 descriptor.dimensionは"2d"であること。 -
もしdescriptor.
dimensionが:"1d"-
-
descriptor.
arrayLayerCountが1であること。
"2d"-
-
descriptor.
arrayLayerCountが1であること。
"2d-array""cube"-
-
descriptor.
arrayLayerCountが6であること。
"cube-array"-
-
descriptor.
arrayLayerCountが6の倍数であること。
"3d"-
-
descriptor.
arrayLayerCountが1であること。
-
-
viewを新しい
GPUTextureViewオブジェクトとする。 -
view.
[[texture]]にthisを設定。 -
view.
[[descriptor]]にdescriptorを設定。 -
もしdescriptor.
usageにRENDER_ATTACHMENTが含まれる場合:-
renderExtentにcompute render extent([this.
width, this.height, this.depthOrArrayLayers], descriptor.baseMipLevel)を設定。 -
view.
[[renderExtent]]にrenderExtentを設定。
-
-
GPUTextureView
textureに対してGPUTextureViewDescriptor
descriptorの既定値を解決する場合、以下のデバイスタイムライン手順を実行:
-
resolvedをdescriptorのコピーとする。
-
resolved.
mipLevelCountが指定されていない場合: resolved.mipLevelCountにtexture.mipLevelCount− resolved.baseMipLevelを設定。 -
resolved.
arrayLayerCountが指定されていない場合、かつ resolved.dimensionが:"1d","2d", または"3d"-
resolved.
arrayLayerCountに1を設定。 "cube"-
resolved.
arrayLayerCountに6を設定。 "2d-array"または"cube-array"-
resolved.
arrayLayerCountにtextureの配列レイヤー数 − resolved.baseArrayLayerを設定。
-
resolvedを返す。
GPUTexture
textureの配列レイヤー数を決定する場合、以下の手順:
-
texture.
dimensionが:"1d"または"3d"-
1を返す。 "2d"-
texture.
depthOrArrayLayersを返す。
6.3. テクスチャフォーマット
フォーマット名は、コンポーネントの順序、各コンポーネントのビット数、コンポーネントのデータ型を指定します。
-
r,g,b,a= 赤、緑、青、アルファ -
unorm= 符号なし正規化 -
snorm= 符号付き正規化 -
uint= 符号なし整数 -
sint= 符号付き整数 -
float= 浮動小数点
フォーマットに-srgbサフィックスが付いている場合、シェーダ内で色値の読み書き時にsRGB変換(ガンマ⇔リニア)が適用されます。圧縮テクスチャフォーマットはfeaturesによって提供されます。命名規則は本規約に従い、テクスチャ名をプレフィックスとして使用します(例:etc2-rgba8unorm)。
テクセルブロックは、画素ベースのGPUTextureFormatテクスチャでは単一のアドレス可能な要素、
ブロックベース圧縮GPUTextureFormatテクスチャでは単一の圧縮ブロックです。
テクセルブロック幅およびテクセルブロック高さは、1つのテクセルブロックの寸法を指定します。
-
画素ベースの
GPUTextureFormatの場合、 テクセルブロック幅・テクセルブロック高さは常に1です。 -
ブロックベース圧縮
GPUTextureFormatの場合、 テクセルブロック幅は1つのテクセルブロックの各行のテクセル数、 テクセルブロック高さは1つのテクセルブロックのテクセル行数です。全フォーマットの値は§ 26.1 テクスチャフォーマットの機能参照。
テクセルブロックコピーフットプリントは、あるGPUTextureFormatのアスペクトについて、
テクセルコピー時に1つのテクセルブロックが占有するバイト数です(該当する場合)。
注:
テクセルブロックメモリコストは、GPUTextureFormatの1つのテクセルブロックを格納するのに必要なバイト数です。全てのフォーマットで厳密には定義されていません。
この値は参考情報であり、規定値ではありません。
enum { // 8-bit formatsGPUTextureFormat ,"r8unorm" ,"r8snorm" ,"r8uint" , // 16-bit formats"r8sint" ,"r16unorm" ,"r16snorm" ,"r16uint" ,"r16sint" ,"r16float" ,"rg8unorm" ,"rg8snorm" ,"rg8uint" , // 32-bit formats"rg8sint" ,"r32uint" ,"r32sint" ,"r32float" ,"rg16unorm" ,"rg16snorm" ,"rg16uint" ,"rg16sint" ,"rg16float" ,"rgba8unorm" ,"rgba8unorm-srgb" ,"rgba8snorm" ,"rgba8uint" ,"rgba8sint" ,"bgra8unorm" , // Packed 32-bit formats"bgra8unorm-srgb" ,"rgb9e5ufloat" ,"rgb10a2uint" ,"rgb10a2unorm" , // 64-bit formats"rg11b10ufloat" ,"rg32uint" ,"rg32sint" ,"rg32float" ,"rgba16unorm" ,"rgba16snorm" ,"rgba16uint" ,"rgba16sint" , // 128-bit formats"rgba16float" ,"rgba32uint" ,"rgba32sint" , // Depth/stencil formats"rgba32float" ,"stencil8" ,"depth16unorm" ,"depth24plus" ,"depth24plus-stencil8" , // "depth32float-stencil8" feature"depth32float" , // BC compressed formats usable if "texture-compression-bc" is both // supported by the device/user agent and enabled in requestDevice."depth32float-stencil8" ,"bc1-rgba-unorm" ,"bc1-rgba-unorm-srgb" ,"bc2-rgba-unorm" ,"bc2-rgba-unorm-srgb" ,"bc3-rgba-unorm" ,"bc3-rgba-unorm-srgb" ,"bc4-r-unorm" ,"bc4-r-snorm" ,"bc5-rg-unorm" ,"bc5-rg-snorm" ,"bc6h-rgb-ufloat" ,"bc6h-rgb-float" ,"bc7-rgba-unorm" , // ETC2 compressed formats usable if "texture-compression-etc2" is both // supported by the device/user agent and enabled in requestDevice."bc7-rgba-unorm-srgb" ,"etc2-rgb8unorm" ,"etc2-rgb8unorm-srgb" ,"etc2-rgb8a1unorm" ,"etc2-rgb8a1unorm-srgb" ,"etc2-rgba8unorm" ,"etc2-rgba8unorm-srgb" ,"eac-r11unorm" ,"eac-r11snorm" ,"eac-rg11unorm" , // ASTC compressed formats usable if "texture-compression-astc" is both // supported by the device/user agent and enabled in requestDevice."eac-rg11snorm" ,"astc-4x4-unorm" ,"astc-4x4-unorm-srgb" ,"astc-5x4-unorm" ,"astc-5x4-unorm-srgb" ,"astc-5x5-unorm" ,"astc-5x5-unorm-srgb" ,"astc-6x5-unorm" ,"astc-6x5-unorm-srgb" ,"astc-6x6-unorm" ,"astc-6x6-unorm-srgb" ,"astc-8x5-unorm" ,"astc-8x5-unorm-srgb" ,"astc-8x6-unorm" ,"astc-8x6-unorm-srgb" ,"astc-8x8-unorm" ,"astc-8x8-unorm-srgb" ,"astc-10x5-unorm" ,"astc-10x5-unorm-srgb" ,"astc-10x6-unorm" ,"astc-10x6-unorm-srgb" ,"astc-10x8-unorm" ,"astc-10x8-unorm-srgb" ,"astc-10x10-unorm" ,"astc-10x10-unorm-srgb" ,"astc-12x10-unorm" ,"astc-12x10-unorm-srgb" ,"astc-12x12-unorm" , };"astc-12x12-unorm-srgb"
"depth24plus"
および"depth24plus-stencil8"
フォーマットのdepth成分は、24ビットdepth値または"depth32float"
値として実装される場合があります。
stencil8
フォーマットは実際の"stencil8"、または"depth24stencil8"(depthアスペクトは非表示・アクセス不可)として実装される場合があります。
-
24ビットdepthの場合、1ULPは1 / (224 − 1)で一定です。
-
depth32floatの場合、1ULPは最大1 / (224)で値によって異なります。
フォーマットがレンダー可能であるとは、カラー・レンダー可能フォーマットまたは深度・ステンシルフォーマットの場合です。
§ 26.1.1 プレーンカラーフォーマットでRENDER_ATTACHMENT
機能を持つものはカラー・レンダー可能フォーマットです。他はカラー・レンダー可能フォーマットではありません。
深度・ステンシルフォーマットはすべてレンダー可能です。
レンダー可能フォーマットは、レンダーパイプラインのブレンディングで使用可能な場合ブレンド可能にもなります。 § 26.1 テクスチャフォーマットの機能参照。
フォーマットがフィルタ可能であるとは、
GPUTextureSampleType
"float"
("unfilterable-float"のみでない)をサポートし、
"filtering"
GPUSamplerで利用可能な場合です。
§ 26.1 テクスチャフォーマットの機能参照。
引数:
-
GPUTextureFormatformat -
GPUTextureAspectaspect
戻り値: GPUTextureFormat
またはnull
-
aspectが:
"all"-
formatを返す。
"depth-only""stencil-only"-
formatがdepth-stencil-formatの場合: formatのアスペクト専用フォーマット(§ 26.1.2 深度ステンシルフォーマット)または aspectが存在しなければ
nullを返す。
-
nullを返す。
一部のテクスチャフォーマットの使用にはGPUDeviceでfeatureを有効化する必要があります。
新フォーマットは仕様に追加される場合があるため、enum値が実装で未知な場合もあります。
実装間の挙動を揃えるため、featureが有効でない場合にフォーマットを使おうとすると例外が投げられます(未対応フォーマット時と同じ挙動)。
§ 26.1 テクスチャフォーマットの機能で、どのGPUTextureFormatがfeature必須か確認できます。
GPUTextureFormat
format,
論理device device) の現行標準タイムライン手順:
-
formatがfeature必須で、device.
[[features]]がfeatureを含まない場合:-
TypeErrorを投げる。
-
6.4. GPUExternalTexture
GPUExternalTexture
は外部動画フレームをラップするサンプル可能な2Dテクスチャです。
不変のスナップショットであり、その内容はWebGPU内外(動画フレームの進行など)で変化しません。
GPUExternalTexture
は
externalTexture
バインドグループレイアウトエントリメンバーでバインド可能です。
このメンバーは複数のバインディングスロットを使用します(詳細はそちら参照)。
GPUExternalTexture
はインポート元のコピーなしで実装できる場合もありますが、
実装依存です。
基盤表現の所有権は排他または他オーナー(動画デコーダ等)との共有の場合もあり、アプリケーションからは不可視です。
外部テクスチャの基盤表現は(正確なサンプリング挙動以外)観測不可ですが、一般的には次が含まれます:
-
最大3個の2Dプレーン(例:RGBA、Y+UV、Y+U+V)
-
座標変換用メタデータ(クロップ・回転)
-
指定の出力色空間への変換メタデータ(行列、ガンマ、3D LUT)
実装内部の構成は時期・システム・UA・メディアソース・同一動画内フレーム間でも一貫しない場合があります。 多様な表現に対応するため、各外部テクスチャで以下を保守的にバインディングします:
-
最大3プレーン用サンプルテクスチャバインディング
-
3D LUT用サンプルテクスチャバインディング
-
3D LUT用サンプラーバインディング
-
メタデータ用ユニフォームバッファバインディング
[Exposed =(Window ,Worker ),SecureContext ]interface GPUExternalTexture { };GPUExternalTexture includes GPUObjectBase ;
GPUExternalTexture
には以下の不変プロパティがあります:
[[descriptor]], 型GPUExternalTextureDescriptor, 読み取り専用-
このテクスチャ作成時のディスクリプタ。
GPUExternalTexture
には以下の不変プロパティがあります:
[[expired]], 型boolean、初期値false-
オブジェクトが期限切れ(利用不可)かどうか。
注:
[[destroyed]]スロットと似ているが、こちらはtrueからfalseに戻る場合もある。
6.4.1. 外部テクスチャのインポート
外部テクスチャは外部動画オブジェクトからimportExternalTexture()
を用いて作成します。
HTMLVideoElement
から作成された外部テクスチャは、他のリソースのように手動やガベージコレクションではなく、インポート後にタスク内で自動的に期限切れ(破棄)となります。
外部テクスチャが期限切れになると、その[[expired]]
スロットがtrueに変わります。
VideoFrame
から作成された外部テクスチャは、元のVideoFrame
がclose(明示的にclose()呼び出し、または他の手段)された時のみ期限切れ(破棄)となります。
注:decode()
でも述べられている通り、著者はデコーダの停止を防ぐため、出力VideoFrame
にclose()
を推奨します。
インポート後のVideoFrame
がcloseされずに破棄された場合、インポート済みGPUExternalTexture
オブジェクトが生きている限り、VideoFrameも生き続けます。
両方とも破棄されるまでVideoFrameはガベージコレクトされません。
ガベージコレクションは予測できないため、これでもビデオデコーダが停止する可能性があります。
GPUExternalTexture
が期限切れになると、importExternalTexture()
を再度呼び出す必要があります。
ただし、ユーザーエージェントは期限切れを解除し、同じGPUExternalTexture
を返す場合があります(新しいものを生成しない)。これは、アプリケーションの実行が動画フレームレート(例:requestVideoFrameCallback()使用)と一致しない限り、一般的に起こります。
同じオブジェクトが再び返された場合、比較は等しくなり、以前のオブジェクトを参照しているGPUBindGroupやGPURenderBundleなどは引き続き使用可能です。
dictionary :GPUExternalTextureDescriptor GPUObjectDescriptorBase {required (HTMLVideoElement or VideoFrame )source ;PredefinedColorSpace colorSpace = "srgb"; };
GPUExternalTextureDescriptor
辞書には以下のメンバーがあります:
source, 型(HTMLVideoElement or VideoFrame)-
外部テクスチャをインポートする動画ソース。ソースサイズは外部ソース寸法表に従って決定されます。
colorSpace, 型 PredefinedColorSpace(デフォルト値"srgb")-
sourceの画像内容を読み込み時に変換する色空間。
importExternalTexture(descriptor)-
指定した画像ソースをラップした
GPUExternalTextureを作成します。呼び出し元:GPUDevicethis.引数:
GPUDevice.importExternalTexture(descriptor) メソッドの引数。 パラメータ 型 Nullable Optional 説明 descriptorGPUExternalTextureDescriptor✘ ✘ 外部画像ソースオブジェクト(および作成オプション)を指定。 戻り値:
GPUExternalTexture現行標準タイムライン手順:
-
sourceをdescriptor.
sourceとする。 -
現在のsource画像内容が、同じdescriptor(
label除く)で以前に呼び出されたimportExternalTexture()と同じであり、UAが再利用を選択した場合:-
previousResultを以前返された
GPUExternalTextureとする。 -
previousResult.
[[expired]]をfalseにし、基盤リソースの所有権を更新する。 -
resultをpreviousResultとする。
注: これにより、アプリケーションが重複インポートを検出し、依存オブジェクト(
GPUBindGroupなど)を再生成せずに済みます。 実装は、1つのフレームが複数GPUExternalTextureでラップされるケースにも対応する必要があります(インポートメタデータcolorSpaceは同一フレームでも変更可能)。それ以外の場合:
-
sourceがorigin-cleanでない場合、
SecurityErrorを投げてreturn。 -
usabilityを? 画像引数の利用性の確認(source)とする。
-
usabilityが
goodでない場合: -
dataを、現在のsource画像内容をdescriptor.
colorSpaceへ非プリマルチアルファで変換した結果とする。この変換で[0, 1]範囲外の値になる場合があります。クランプが必要ならサンプリング後に行えます。
注: コピーのように記述されていますが、実際は読み取り専用の基盤データと変換用メタデータへの参照として実装可能です。
-
resultをdataをラップした新しい
GPUExternalTextureオブジェクトとする。
-
-
sourceが
HTMLVideoElementの場合、 自動期限切れタスクをキュー(device this、次の手順):-
result.
[[expired]]をtrueにし、基盤リソースの所有権を解放する。
注:
HTMLVideoElementはテクスチャをサンプリングする同じタスクでインポートすること(通常requestVideoFrameCallbackやrequestAnimationFrame()を使う)。 そうしないと、アプリケーションが使い終わる前にこれらの手順でテクスチャが破棄される可能性があります。 -
-
sourceが
VideoFrameの場合、 sourceがcloseされた時、次の手順を実行:-
result.
[[expired]]をtrueにする。
-
-
resultを返す。
-
const videoElement= document. createElement( 'video' ); // ... videoElementのセットアップ、ready待ち ... function frame() { requestAnimationFrame( frame); // 毎アニメーションフレームで必ず再インポート。importは期限切れの可能性が高い。 // ブラウザは過去フレームをキャッシュ・再利用する場合があり、その際 // 同じGPUExternalTextureオブジェクトを再び返すことがある。 // この場合、古いバインドグループも有効。 const externalTexture= gpuDevice. importExternalTexture({ source: videoElement}); // ... externalTextureで描画 ... } requestAnimationFrame( frame);
const videoElement= document. createElement( 'video' ); // ... videoElementのセットアップ ... function frame() { videoElement. requestVideoFrameCallback( frame); // フレーム進行が確実なため、毎回再インポート const externalTexture= gpuDevice. importExternalTexture({ source: videoElement}); // ... externalTextureで描画 ... } videoElement. requestVideoFrameCallback( frame);
6.5. 外部テクスチャバインディングのサンプリング
externalTexture
バインディングポイントは、GPUExternalTexture
オブジェクト(動画など動的画像ソース)をバインドできます。また、GPUTexture
やGPUTextureViewにも対応しています。
注:
GPUTexture
やGPUTextureView
をexternalTextureバインディングにバインドした場合、
RGBA単一プレーン・クロップ/回転/色変換なしのGPUExternalTexture
と同じ扱いになります。
外部テクスチャはWGSLではtexture_externalで表され、textureLoadやtextureSampleBaseClampToEdgeで読み取れます。
textureSampleBaseClampToEdgeに渡すsamplerは基盤テクスチャのサンプリングに使われます。
バインディングリソース型がGPUExternalTextureの場合、
結果はcolorSpaceで指定された色空間となります。
実装依存で、サンプラー(およびフィルタリング)が基底値から指定色空間への変換の前後どちらで適用されるかは異なります。
注: 内部表現がRGBAプレーンの場合、サンプリングは通常の2Dテクスチャと同様です。 複数プレーン(例:Y+UV)の場合、サンプラーは各基盤テクスチャを個別にサンプリングし、YUV→指定色空間変換前に適用されます。
7. サンプラー
7.1. GPUSampler
GPUSampler
はシェーダでテクスチャリソースデータを解釈するための変換・フィルタ情報を符号化します。
GPUSampler
はcreateSampler()
で作成されます。
[Exposed =(Window ,Worker ),SecureContext ]interface GPUSampler { };GPUSampler includes GPUObjectBase ;
GPUSampler
には以下の不変プロパティがあります:
[[descriptor]], 型GPUSamplerDescriptor、読み取り専用-
この
GPUSamplerの作成時に使用したGPUSamplerDescriptor。 [[isComparison]], 型boolean、読み取り専用-
この
GPUSamplerが比較サンプラーとして利用されるかどうか。 [[isFiltering]], 型boolean、読み取り専用-
この
GPUSamplerがテクスチャの複数サンプルを重み付けするかどうか。
7.1.1. GPUSamplerDescriptor
GPUSamplerDescriptor
はGPUSampler
の作成時オプションを指定します。
dictionary :GPUSamplerDescriptor GPUObjectDescriptorBase {GPUAddressMode addressModeU = "clamp-to-edge";GPUAddressMode addressModeV = "clamp-to-edge";GPUAddressMode addressModeW = "clamp-to-edge";GPUFilterMode magFilter = "nearest";GPUFilterMode minFilter = "nearest";GPUMipmapFilterMode mipmapFilter = "nearest";float lodMinClamp = 0;float lodMaxClamp = 32;GPUCompareFunction compare ; [Clamp ]unsigned short maxAnisotropy = 1; };
addressModeU, 型 GPUAddressMode(デフォルト値"clamp-to-edge")addressModeV, 型 GPUAddressMode(デフォルト値"clamp-to-edge")addressModeW, 型 GPUAddressMode(デフォルト値"clamp-to-edge")-
テクスチャの幅・高さ・深度座標それぞれの
アドレスモード指定。 magFilter, 型 GPUFilterMode(デフォルト値"nearest")-
サンプリング領域が1テクセル以下のときのサンプリング動作。
minFilter, 型 GPUFilterMode(デフォルト値"nearest")-
サンプリング領域が1テクセルより大きいときのサンプリング動作。
mipmapFilter, 型 GPUMipmapFilterMode(デフォルト値"nearest")-
ミップマップレベル間のサンプリング動作。
lodMinClamp, 型 float(デフォルト値0)lodMaxClamp, 型 float(デフォルト値32)-
テクスチャサンプリング時に内部的に使われる最小・最大レベルオブディテール。
compare, 型 GPUCompareFunction-
指定した場合、サンプラーは指定
GPUCompareFunctionで比較サンプラーになります。注: 比較サンプラーはフィルタリング使用可能ですが、結果は実装依存・通常のフィルタリングルールと異なる場合があります。
maxAnisotropy, 型 unsigned short(デフォルト値1)-
サンプラーで使われる最大異方性値クランプ指定。
maxAnisotropy> 1かつ実装が対応している場合、異方性フィルタリング有効。異方性フィルタリングは斜め視点テクスチャの画質向上。
maxAnisotropy値が高いほどフィルタリング時の最大異方性比。
レベルオブディテール(LOD)はテクスチャサンプリング時に選択されるミップレベルを示します。シェーダのtextureSampleLevel等で明示指定、またはテクスチャ座標の微分から暗黙決定されます。
注: 暗黙LOD計算例はScale Factor Operation, LOD Operation and Image Level Selection(Vulkan 1.3仕様)参照。
GPUAddressMode
はサンプリングテクセルがテクスチャ範囲外のときのサンプラー動作指定。
enum {GPUAddressMode "clamp-to-edge" ,"repeat" ,"mirror-repeat" , };
"clamp-to-edge"-
テクスチャ座標は0.0~1.0の範囲にクランプ。
"repeat"-
テクスチャ座標はテクスチャの反対側へラップ。
"mirror-repeat"-
テクスチャ座標は反対側へラップしつつ、座標の整数部が奇数のときテクスチャを反転。
GPUFilterMode
およびGPUMipmapFilterMode
はサンプリング領域が1テクセルちょうどでない場合のサンプラー動作指定。
注: 各種フィルターモードでどのテクセルがサンプルされるかの例はTexel Filtering(Vulkan 1.3仕様)参照。
enum {GPUFilterMode "nearest" ,"linear" , };enum {GPUMipmapFilterMode ,"nearest" , };"linear"
"nearest"-
テクスチャ座標に最も近いテクセルの値を返す。
"linear"-
各次元で2テクセル選び、その値を線形補間して返す。
GPUCompareFunction
は比較サンプラーの挙動指定。シェーダで比較サンプラー使用時、depth_refと取得テクセル値を比較し、その判定結果(合格1.0f/不合格0.0f)を生成。
比較後、テクスチャフィルタリング有効ならフィルタリングが行われ、判定結果同士が混合され[0, 1]範囲の値となる。フィルタリングは通常通り動作すべきだが、精度低下や混合なしの可能性もある。
enum {GPUCompareFunction "never" ,"less" ,"equal" ,"less-equal" ,"greater" ,"not-equal" ,"greater-equal" ,"always" , };
"never"-
比較判定は常に不合格。
"less"-
与えられた値がサンプル値より小さい場合に合格。
"equal"-
与えられた値がサンプル値と等しい場合に合格。
"less-equal"-
与えられた値がサンプル値以下の場合に合格。
"greater"-
与えられた値がサンプル値より大きい場合に合格。
"not-equal"-
与えられた値がサンプル値と異なる場合に合格。
"greater-equal"-
与えられた値がサンプル値以上の場合に合格。
"always"-
比較判定は常に合格。
7.1.2. サンプラーの作成
createSampler(descriptor)-
GPUSamplerを作成します。呼び出し元:GPUDevicethis.引数:
GPUDevice.createSampler(descriptor) メソッドの引数。 パラメータ 型 Nullable Optional 説明 descriptorGPUSamplerDescriptor✘ ✔ 作成する GPUSamplerの説明。戻り値:
GPUSampler現行標準タイムライン手順:
-
sを! 新しいWebGPUオブジェクトの生成(this,
GPUSampler, descriptor)とする。 -
thisのデバイスタイムラインでinitialization stepsを発行。
-
sを返す。
デバイスタイムライン initialization steps:-
以下の条件が満たされない場合検証エラー生成、sの無効化、return。
-
thisが失われていないこと。
-
descriptor.
lodMinClamp≥ 0。 -
descriptor.
lodMaxClamp≥ descriptor.lodMinClamp。 -
descriptor.
maxAnisotropy≥ 1。注: 多くの実装は
maxAnisotropyを1~16の範囲でサポート。指定値はプラットフォーム最大値にクランプされます。 -
descriptor.
maxAnisotropy> 1の場合:-
descriptor.
magFilter, descriptor.minFilter, descriptor.mipmapFilterがすべて"linear"であること。
-
-
-
s.
[[descriptor]]にdescriptorを設定。 -
s.
[[isComparison]]を、s.[[descriptor]]のcompare属性がnullまたは未定義ならfalse、それ以外ならtrueに設定。 -
s.
[[isFiltering]]を、minFilter、magFilter、mipmapFilterのいずれも"linear"でなければfalse、いずれかが"linear"ならtrueに設定。
-
GPUSampler生成例:
const sampler= gpuDevice. createSampler({ addressModeU: 'repeat' , addressModeV: 'repeat' , magFilter: 'linear' , minFilter: 'linear' , mipmapFilter: 'linear' , });
8. リソースバインディング
8.1. GPUBindGroupLayout
GPUBindGroupLayout
は、GPUBindGroup
でバインドされたリソース群と、シェーダステージでのアクセス性とのインターフェースを定義します。
[Exposed =(Window ,Worker ),SecureContext ]interface GPUBindGroupLayout { };GPUBindGroupLayout includes GPUObjectBase ;
GPUBindGroupLayout
には以下の不変プロパティがあります:
[[descriptor]], 型GPUBindGroupLayoutDescriptor、読み取り専用
8.1.1. バインドグループレイアウトの作成
GPUBindGroupLayout
はGPUDevice.createBindGroupLayout()で作成します。
dictionary :GPUBindGroupLayoutDescriptor GPUObjectDescriptorBase {required sequence <GPUBindGroupLayoutEntry >entries ; };
GPUBindGroupLayoutDescriptor
辞書には以下のメンバーがあります:
entries, 型 sequence<GPUBindGroupLayoutEntry>-
バインドグループのシェーダリソースバインディングを記述するエントリのリスト。
GPUBindGroupLayoutEntry
は、GPUBindGroupLayoutに含める1つのシェーダリソースバインディングを記述します。
dictionary {GPUBindGroupLayoutEntry required GPUIndex32 binding ;required GPUShaderStageFlags visibility ;GPUBufferBindingLayout buffer ;GPUSamplerBindingLayout sampler ;GPUTextureBindingLayout texture ;GPUStorageTextureBindingLayout storageTexture ;GPUExternalTextureBindingLayout externalTexture ; };
GPUBindGroupLayoutEntry
辞書には以下のメンバーがあります:
binding, 型 GPUIndex32-
GPUBindGroupLayout内でリソースバインディングを一意に識別するID。GPUBindGroupEntry.bindingおよびGPUShaderModuleの@binding属性に対応。 visibility, 型 GPUShaderStageFlags-
GPUShaderStageメンバーのビットセット。 各ビットが立っていると、GPUBindGroupLayoutEntryのリソースが対応シェーダステージからアクセス可能。 buffer, 型 GPUBufferBindingLayoutsampler, 型 GPUSamplerBindingLayouttexture, 型 GPUTextureBindingLayoutstorageTexture, 型 GPUStorageTextureBindingLayoutexternalTexture, 型 GPUExternalTextureBindingLayout-
これらのうち正確に1つだけ設定し、バインディング型を示します。 各メンバーの内容はその型固有のオプションを指定します。
createBindGroup()の対応リソースは、このバインディングのバインディングリソース型に従う必要があります。
typedef [EnforceRange ]unsigned long ; [GPUShaderStageFlags Exposed =(Window ,Worker ),SecureContext ]namespace {GPUShaderStage const GPUFlagsConstant VERTEX = 0x1;const GPUFlagsConstant FRAGMENT = 0x2;const GPUFlagsConstant COMPUTE = 0x4; };
GPUShaderStage
には以下のフラグが含まれ、これにより該当GPUBindGroupEntry
がこのGPUBindGroupLayoutEntry
に対してどのシェーダーステージから可視かを示します:
VERTEX-
バインドグループエントリは頂点シェーダーからアクセス可能。
FRAGMENT-
バインドグループエントリはフラグメントシェーダーからアクセス可能。
COMPUTE-
バインドグループエントリは計算シェーダーからアクセス可能。
GPUBindGroupLayoutEntry
のbinding memberは、
どのGPUBindGroupLayoutEntry
メンバーが定義されているかによって決まります:
buffer、
sampler、
texture、
storageTexture、
または
externalTexture。
いずれか1つだけがGPUBindGroupLayoutEntry
で定義可能です。
各メンバーには対応するGPUBindingResource型があり、
各バインディング型には対応する内部用途があります。以下の表参照:
| バインディングメンバー | リソース型 | バインディング型 | バインディング用途 |
|---|---|---|---|
buffer
| GPUBufferBinding(または GPUBuffer
略記として)
| "uniform"
| constant |
"storage"
| storage | ||
"read-only-storage"
| storage-read | ||
sampler
| GPUSampler
| "filtering"
| constant |
"non-filtering"
| |||
"comparison"
| |||
texture
| GPUTextureView(または GPUTexture
略記として)
| "float"
| constant |
"unfilterable-float"
| |||
"depth"
| |||
"sint"
| |||
"uint"
| |||
storageTexture
| GPUTextureView(または GPUTexture
略記として)
| "write-only"
| storage |
"read-write"
| |||
"read-only"
| storage-read | ||
externalTexture
| GPUExternalTextureまたは GPUTextureView(または GPUTexture
略記として)
| constant |
GPUBindGroupLayoutEntry
値entriesが
バインディングスロット制限超過となるのは、supported
limitslimitsにおいて、制限値を超えてスロット数が使用された場合です。
各エントリは複数の制限に対して複数スロットを使用する場合があります。
デバイスタイムライン手順:
-
entries内の各entryについて、次の場合:
- entry.
buffer?.typeが"uniform"かつ entry.buffer?.hasDynamicOffsetがtrueの場合 -
maxDynamicUniformBuffersPerPipelineLayoutスロットを1個使用したとみなす。 - entry.
buffer?.typeが"storage"かつ entry.buffer?.hasDynamicOffsetがtrueの場合 -
maxDynamicStorageBuffersPerPipelineLayoutスロットを1個使用したとみなす。
- entry.
-
各シェーダーステージstage( «
VERTEX,FRAGMENT,COMPUTE»)について:-
stageを含むentry.
visibilityの各entryについて、以下の場合:- entry.
buffer?.typeが"uniform"の場合 -
maxUniformBuffersPerShaderStageスロットを1個使用したとみなす。 - entry.
buffer?.typeが"storage"または"read-only-storage"の場合 -
maxStorageBuffersPerShaderStageスロットを1個使用したとみなす。 - entry.
samplerが存在する場合 -
maxSamplersPerShaderStageスロットを1個使用したとみなす。 - entry.
textureが存在する場合 -
maxSampledTexturesPerShaderStageスロットを1個使用したとみなす。 - entry.
storageTextureが存在する場合 -
maxStorageTexturesPerShaderStageスロットを1個使用したとみなす。 - entry.
externalTextureが存在する場合 -
maxSampledTexturesPerShaderStageスロット4個、maxSamplersPerShaderStageスロット1個、maxUniformBuffersPerShaderStageスロット1個 を使用したとみなす。注: この挙動の説明は
GPUExternalTextureを参照。
- entry.
-
enum {GPUBufferBindingType ,"uniform" ,"storage" , };"read-only-storage" dictionary {GPUBufferBindingLayout GPUBufferBindingType type = "uniform";boolean hasDynamicOffset =false ;GPUSize64 minBindingSize = 0; };
GPUBufferBindingLayout
辞書には以下のメンバーがあります:
type, 型 GPUBufferBindingType(デフォルト値"uniform")-
このバインディングにバインドされるバッファに要求される型を示します。
hasDynamicOffset, 型 boolean(デフォルト値false)-
このバインディングが動的オフセットを要求するかどうかを示します。
minBindingSize, 型 GPUSize64(デフォルト値0)-
このバインドポイントで使用されるバッファバインディングの最小
sizeを示します。バインディングは常にこのサイズに対して
createBindGroup()内で検証されます。この値が0でない場合、パイプライン作成時にさらに、変数の最小バッファバインディングサイズ以上であることが検証されます。
この値が0の場合、パイプライン作成時には無視され、代わりに描画/ディスパッチコマンドが
GPUBindGroup内の各バインディングが変数の最小バッファバインディングサイズを満たすか検証します。注: 実行時検証は、
sampleTypeやformatのような他の早期検証項目にも理論上可能ですが、現状ではパイプライン作成時のみ検証されます。 ただし実行時検証はコスト・複雑性の増加につながるため、最も利便性に影響するminBindingSizeにのみ導入されています。
enum {GPUSamplerBindingType ,"filtering" ,"non-filtering" , };"comparison" dictionary {GPUSamplerBindingLayout GPUSamplerBindingType type = "filtering"; };
GPUSamplerBindingLayout
辞書には以下のメンバーがあります:
type, 型 GPUSamplerBindingType(デフォルト値"filtering")-
このバインディングにバインドされるサンプラーに要求される型を示します。
enum {GPUTextureSampleType ,"float" ,"unfilterable-float" ,"depth" ,"sint" , };"uint" dictionary {GPUTextureBindingLayout GPUTextureSampleType sampleType = "float";GPUTextureViewDimension viewDimension = "2d";boolean multisampled =false ; };
GPUTextureBindingLayout
辞書には以下のメンバーがあります:
sampleType, 型 GPUTextureSampleType(デフォルト値"float")-
このバインディングにバインドされるテクスチャビューに要求される型を示します。
viewDimension, 型 GPUTextureViewDimension(デフォルト値"2d")-
このバインディングにバインドされるテクスチャビューに要求される
dimensionを示します。 multisampled, 型 boolean(デフォルト値false)-
このバインディングにバインドされるテクスチャビューがマルチサンプルである必要があるかどうかを示します。
enum {GPUStorageTextureAccess ,"write-only" ,"read-only" , };"read-write" dictionary {GPUStorageTextureBindingLayout GPUStorageTextureAccess access = "write-only";required GPUTextureFormat format ;GPUTextureViewDimension viewDimension = "2d"; };
GPUStorageTextureBindingLayout
辞書には以下のメンバーがあります:
access, 型 GPUStorageTextureAccess(デフォルト値"write-only")-
このバインディングのアクセスモード(読み取り・書き込み可能性)を示します。
format, 型 GPUTextureFormat-
このバインディングにバインドされるテクスチャビューの要求
format。 viewDimension, 型 GPUTextureViewDimension(デフォルト値"2d")-
このバインディングにバインドされるテクスチャビューに要求される
dimensionを示します。
dictionary { };GPUExternalTextureBindingLayout
GPUBindGroupLayout
オブジェクトは以下のデバイスタイムラインプロパティを持ちます:
[[entryMap]], 型 ordered map<GPUSize32,GPUBindGroupLayoutEntry>、読み取り専用-
この
GPUBindGroupLayoutが記述する、バインディングインデックス→GPUBindGroupLayoutEntryのマップ。 [[dynamicOffsetCount]], 型GPUSize32、読み取り専用-
この
GPUBindGroupLayoutに動的オフセット付きバッファバインディング数。 [[exclusivePipeline]], 型GPUPipelineBase?、読み取り専用-
この
GPUBindGroupLayoutを作成したパイプライン(デフォルトパイプラインレイアウトの一部として作成された場合)。nullでない場合、これを使って作成したGPUBindGroupは指定GPUPipelineBaseでのみ使用可能。
createBindGroupLayout(descriptor)-
GPUBindGroupLayoutを作成します。呼び出し元:GPUDevicethis.引数:
GPUDevice.createBindGroupLayout(descriptor) メソッドの引数。 パラメータ 型 Nullable Optional 説明 descriptorGPUBindGroupLayoutDescriptor✘ ✘ 作成する GPUBindGroupLayoutの説明。戻り値:
GPUBindGroupLayout現行標準タイムライン手順:
-
descriptor.
entries内の各GPUBindGroupLayoutEntryentryについて:-
entry.
storageTextureが存在する場合:-
? テクスチャフォーマット必須機能の検証を entry.
storageTexture.formatとthis.[[device]]で行う。
-
-
-
layoutを! 新しいWebGPUオブジェクトの生成(this,
GPUBindGroupLayout, descriptor)とする。 -
thisのデバイスタイムラインでinitialization stepsを発行。
-
layoutを返す。
デバイスタイムライン initialization steps:-
以下の条件が満たされない場合検証エラー生成、layoutの無効化、return。
-
thisが失われていないこと。
-
limitsをthis.
[[device]].[[limits]]とする。 -
descriptor内の各エントリの
bindingが一意。 -
descriptor内の各エントリの
bindingが limits.maxBindingsPerBindGroup未満。 -
descriptor.
entriesがバインディングスロット制限超過でない。 -
descriptor.
entries内の各GPUBindGroupLayoutEntryentryについて:-
entry.
buffer、 entry.sampler、 entry.texture、 entry.storageTexture、 entry.externalTextureのうち正確に1つが存在すること。 -
entry.
visibilityはGPUShaderStageで定義されたビットのみ含む。 -
entry.
visibilityにVERTEXが含まれる場合:-
entry.
bufferが存在する場合、 entry.buffer.typeは"uniform"または"read-only-storage"。 -
entry.
storageTextureが存在する場合、 entry.storageTexture.accessは"read-only"。
-
-
entry.
texture?.multisampledがtrueの場合:-
entry.
texture.viewDimensionは"2d"。 -
entry.
texture.sampleTypeは"float"以外。
-
-
entry.
storageTextureが存在する場合:-
entry.
storageTexture.viewDimensionは"cube"または"cube-array"以外。 -
entry.
storageTexture.formatは、entry.storageTexture.accessに対し§ 26.1.1 プレーンカラー形式表に従いストレージ用途対応のフォーマットであること。
-
-
-
-
layout.
[[descriptor]]にdescriptorを設定。 -
layout.
[[dynamicOffsetCount]]に、descriptor内でbufferが存在するかつbuffer.hasDynamicOffsetがtrueなエントリ数を設定。 -
layout.
[[exclusivePipeline]]にnullを設定。 -
descriptor.
entries内の各GPUBindGroupLayoutEntryentryについて:-
entryをlayout.
[[entryMap]]にentry.bindingをキーとして挿入。
-
-
8.1.2. 互換性
GPUBindGroupLayoutオブジェクトaとbは、以下すべての条件が満たされたときのみグループ同等とみなされます。
-
任意のバインディング番号bindingについて、次のいずれかを満たす:
-
a.
[[entryMap]]とb.[[entryMap]]の両方に存在しない。 -
a.
[[entryMap]][binding] == b.[[entryMap]][binding]
-
バインドグループレイアウトがグループ同等なら、すべての現行標準内容で相互に利用可能です。
8.2. GPUBindGroup
GPUBindGroupは、グループ内でまとめてバインドするリソース集合と、それらがシェーダーステージでどのように利用されるかを定義します。
[Exposed =(Window ,Worker ),SecureContext ]interface GPUBindGroup { };GPUBindGroup includes GPUObjectBase ;
GPUBindGroupは以下のデバイスタイムラインプロパティを持ちます:
[[layout]], 型GPUBindGroupLayout、読み取り専用-
この
GPUBindGroupに関連付けられているGPUBindGroupLayout。 [[entries]], 型 sequence<GPUBindGroupEntry>、読み取り専用-
この
GPUBindGroupが記述するGPUBindGroupEntryの集合。 [[usedResources]], 型 usage scope、読み取り専用-
このバインドグループが使用するバッファ・テクスチャサブリソースの集合。利用される内部用途フラグのリストも関連付けられます。
GPUBindGroupbindGroupのバインドバッファ範囲は、list<GPUBufferDynamicOffset>
dynamicOffsetsが与えられたとき、以下の手順で算出されます:
-
resultを新しいset<(
GPUBindGroupLayoutEntry,GPUBufferBinding)>として用意。 -
dynamicOffsetIndexを0に設定。
-
bindGroup.
[[entries]]内の各GPUBindGroupEntrybindGroupEntry(bindGroupEntry.bindingでソート済み)について:-
bindGroupLayoutEntryを bindGroup.
[[layout]].[[entryMap]][bindGroupEntry.binding]とする。 -
boundをget as buffer binding(bindGroupEntry.
resource)とする。 -
bindGroupLayoutEntry.
buffer.hasDynamicOffsetの場合:-
bound.
offsetに dynamicOffsets[dynamicOffsetIndex]を加算。 -
dynamicOffsetIndexを1増やす。
-
-
追加 (bindGroupLayoutEntry, bound) を result に。
-
-
resultを返す。
8.2.1. バインドグループの作成
GPUBindGroupはGPUDevice.createBindGroup()で作成します。
dictionary :GPUBindGroupDescriptor GPUObjectDescriptorBase {required GPUBindGroupLayout layout ;required sequence <GPUBindGroupEntry >entries ; };
GPUBindGroupDescriptor
辞書には以下のメンバーがあります:
layout, 型 GPUBindGroupLayout-
このバインドグループのエントリが準拠する
GPUBindGroupLayout。 entries, 型 sequence<GPUBindGroupEntry>-
layoutで記述される各バインディングに対し、シェーダーで公開するリソースを記述するエントリのリスト。
typedef (GPUSampler or GPUTexture or GPUTextureView or GPUBuffer or GPUBufferBinding or GPUExternalTexture );GPUBindingResource dictionary {GPUBindGroupEntry required GPUIndex32 binding ;required GPUBindingResource resource ; };
GPUBindGroupEntry
はGPUBindGroup内でバインドする1つのリソースを記述し、以下のメンバーを持ちます:
binding, 型 GPUIndex32-
この
GPUBindGroup内でリソースバインディングを一意に識別するID。GPUBindGroupLayoutEntry.bindingおよび、GPUShaderModuleの@binding属性に対応。 resource, 型 GPUBindingResource-
バインドするリソース。
GPUSampler、GPUTexture、GPUTextureView、GPUBuffer、GPUBufferBinding、 またはGPUExternalTexture。
GPUBindGroupEntry
は以下のデバイスタイムラインプロパティを持ちます:
[[prevalidatedSize]], 型boolean-
このバインディングエントリが作成時にバッファサイズ検証済みかどうか。
dictionary {GPUBufferBinding required GPUBuffer buffer ;GPUSize64 offset = 0;GPUSize64 size ; };
GPUBufferBinding
はバッファおよびオプションの範囲をリソースとしてバインドするために記述し、以下のメンバーを持ちます:
buffer, 型 GPUBuffer-
バインドする
GPUBuffer。 offset, 型 GPUSize64(デフォルト値0)-
bufferの先頭から、バッファバインディングでシェーダーに公開する範囲の先頭までのバイトオフセット。 size, 型 GPUSize64
createBindGroup(descriptor)-
GPUBindGroupを作成します。呼び出し元:GPUDevicethis.引数:
GPUDevice.createBindGroup(descriptor) メソッドの引数。 パラメータ 型 Nullable Optional 説明 descriptorGPUBindGroupDescriptor✘ ✘ 作成する GPUBindGroupの説明。戻り値:
GPUBindGroup現行標準タイムライン手順:
-
bindGroupを! 新しいWebGPUオブジェクトの生成(this,
GPUBindGroup, descriptor)とする。 -
thisのデバイスタイムラインでinitialization stepsを発行。
-
bindGroupを返す。
デバイスタイムライン initialization steps:-
limitsをthis.
[[device]].[[limits]]とする。 -
以下の条件が満たされない場合検証エラー生成、bindGroupの無効化、return。
descriptor.
entries内の各GPUBindGroupEntrybindingDescriptorについて:-
resourceをbindingDescriptor.
resourceとする。 -
descriptor.
layout.entries内に bindingDescriptor.bindingと等しいGPUBindGroupLayoutEntrylayoutBindingが正確に1つ存在すること。 -
定義されたbinding memberが:
sampler-
-
resourceが
GPUSamplerである。 -
resourceがthisで有効利用可能であること。
-
"filtering"-
resource.
[[isComparison]]がfalse。 "non-filtering"-
resource.
[[isFiltering]]がfalseかつresource.[[isComparison]]がfalse。 "comparison"-
resource.
[[isComparison]]がtrue。
-
texture-
-
resourceが
GPUTextureまたはGPUTextureViewである。 -
resourceがthisで有効利用可能であること。
-
textureViewをget as texture view(resource)とする。
-
textureをtextureView.
[[texture]]とする。 -
layoutBinding.
texture.viewDimensionがtextureViewのdimensionと等しい。 -
layoutBinding.
texture.sampleTypeがtextureViewのformatと互換。 -
textureView.
[[descriptor]].usageがTEXTURE_BINDINGを含む。 -
layoutBinding.
texture.multisampledがtrueならtextureのsampleCount>1、そうでなければ1。
-
storageTexture-
-
resourceが
GPUTextureまたはGPUTextureViewである。 -
resourceがthisで有効利用可能であること。
-
storageTextureViewをget as texture view(resource)とする。
-
textureをstorageTextureView.
[[texture]]とする。 -
layoutBinding.
storageTexture.viewDimensionがstorageTextureViewのdimensionと等しい。 -
layoutBinding.
storageTexture.formatがstorageTextureView.[[descriptor]].formatと等しい。 -
storageTextureView.
[[descriptor]].usageがSTORAGE_BINDINGを含む。 -
storageTextureView.
[[descriptor]].mipLevelCountは1であること。
-
buffer-
-
resourceが
GPUBufferまたはGPUBufferBindingである。 -
bufferBindingをget as buffer binding(resource)とする。
-
bufferBinding.
offsetと bufferBinding.sizeで指定されるバインド範囲がバッファ内にありサイズが0でないこと。 -
effective buffer binding size(bufferBinding) ≥ layoutBinding.
buffer.minBindingSize。 -
"uniform"-
-
effective buffer binding size(bufferBinding) ≤ limits.
maxUniformBufferBindingSize。 -
bufferBinding.
offsetがlimits.minUniformBufferOffsetAlignmentの倍数。
"storage"または"read-only-storage"-
-
effective buffer binding size(bufferBinding) ≤ limits.
maxStorageBufferBindingSize。 -
effective buffer binding size(bufferBinding)が4の倍数。
-
bufferBinding.
offsetがlimits.minStorageBufferOffsetAlignmentの倍数。
-
externalTexture-
-
resourceが
GPUExternalTexture、GPUTexture、 またはGPUTextureViewである。 -
resourceがthisで有効利用可能であること。
-
resourceが:
GPUTextureまたはGPUTextureView-
-
viewをget as texture view(resource)とする。
-
view.
[[descriptor]].usageがTEXTURE_BINDINGを含む。 -
view.
[[descriptor]].dimensionが"2d"であること。 -
view.
[[descriptor]].mipLevelCountが1であること。 -
view.
[[descriptor]].formatが"rgba8unorm"、"bgra8unorm"、 または"rgba16float"であること。 -
view.
[[texture]].sampleCountが1であること。
-
-
-
-
bindGroup.
[[layout]]= descriptor.layout。 -
bindGroup.
[[entries]]= descriptor.entries。 -
bindGroup.
[[usedResources]]= {}。 -
descriptor.
entries内の各GPUBindGroupEntrybindingDescriptorについて:-
internalUsageをlayoutBindingのバインディング用途とする。
-
resourceが参照する各サブリソースを
[[usedResources]]にinternalUsageとして追加。 -
定義されたbinding memberが
bufferかつ layoutBinding.buffer.minBindingSizeが0なら bindingDescriptor.[[prevalidatedSize]]をfalse、それ以外ならtrueとする。
-
-
引数:
-
GPUBindingResourceresource
戻り値: GPUTextureView
-
Assert resourceが
GPUTextureまたはGPUTextureViewである。 -
もしresourceが:
GPUTexture-
-
resource.
createView()を返す。
-
GPUTextureView-
-
resourceを返す。
-
引数:
-
GPUBindingResourceresource
戻り値: GPUBufferBinding
-
Assert resourceが
GPUBufferまたはGPUBufferBindingである。 -
もしresourceが:
GPUBuffer-
-
bufferBindingを新しい
GPUBufferBindingとして用意。 -
bufferBinding.
bufferをresourceに設定。 -
bufferBindingを返す。
-
GPUBufferBinding-
-
resourceを返す。
-
GPUBufferBinding
オブジェクトaとbは、以下すべての条件を満たした場合のみバッファバインディングのエイリアスとみなされます。
注: この計算を行う際、動的オフセットはすでに範囲に適用されています。
8.3. GPUPipelineLayout
GPUPipelineLayout
は、setBindGroup()でコマンドエンコード中にセットされたすべてのGPUBindGroupのリソースと、
GPURenderCommandsMixin.setPipeline
またはGPUComputePassEncoder.setPipelineでセットされたパイプラインのシェーダーとの間のマッピングを定義します。
リソースの完全なバインディングアドレスは次の三つ組みとして定義できます:
-
リソースが可視となるシェーダーステージマスク
-
バインドグループインデックス
-
バインディング番号
アドレスの各要素はパイプラインのバインディング空間ともみなせます。1つのGPUBindGroup
(対応するGPUBindGroupLayout付き)は、固定のバインドグループインデックスに対する空間をカバーします。含まれるバインディングは、そのバインドグループインデックスでシェーダーが利用するリソースのスーパーセットである必要があります。
[Exposed =(Window ,Worker ),SecureContext ]interface GPUPipelineLayout { };GPUPipelineLayout includes GPUObjectBase ;
GPUPipelineLayout
は以下のデバイスタイムラインプロパティを持ちます:
[[bindGroupLayouts]], 型 list<GPUBindGroupLayout>、読み取り専用-
作成時に
GPUPipelineLayoutDescriptor.bindGroupLayoutsで指定されたGPUBindGroupLayoutオブジェクト群。
注: 同じGPUPipelineLayout
を複数のGPURenderPipeline
やGPUComputePipeline
パイプライン間で使用すると、これらのパイプライン間で切り替えが発生してもユーザーエージェントが内部でリソースを再バインドする必要がないことが保証されます。
GPUComputePipeline
オブジェクトXがGPUPipelineLayout.bindGroupLayouts
A, B, Cで作成されたとします。GPUComputePipeline
オブジェクトYはA, D, Cで作成されたとします。コマンドエンコードシーケンスが次の2つのディスパッチであると仮定します:
-
setBindGroup(0, ...)
-
setBindGroup(1, ...)
-
setBindGroup(2, ...)
-
setPipeline(X) -
setBindGroup(1, ...)
-
setPipeline(Y)
この場合、ユーザーエージェントは2回目のdispatchのためにグループスロット2を再バインドする必要があります。これは、GPUPipelineLayout.bindGroupLayouts
のインデックス2のGPUBindGroupLayoutや、
スロット2のGPUBindGroupが変化しなくても発生します。
注: GPUPipelineLayout
の推奨される利用方法は、最も一般的かつ変更頻度の低いバインドグループをレイアウトの「下部」、すなわちバインドグループスロット番号が0や1など低い位置に配置することです。描画呼び出し間で頻繁に変更する必要があるバインドグループほどインデックスを高くします。この一般的なガイドラインにより、ユーザーエージェントは描画呼び出し間の状態変更を最小化し、結果としてCPUオーバーヘッドも低減できます。
8.3.1. パイプラインレイアウトの作成
GPUPipelineLayout
はGPUDevice.createPipelineLayout()で作成されます。
dictionary :GPUPipelineLayoutDescriptor GPUObjectDescriptorBase {required sequence <GPUBindGroupLayout ?>bindGroupLayouts ; };
GPUPipelineLayoutDescriptor
辞書はパイプラインが用いるすべてのGPUBindGroupLayoutを定義し、次のメンバーを持ちます:
bindGroupLayouts, 型sequence<GPUBindGroupLayout?>-
パイプラインが利用するオプションの
GPUBindGroupLayoutのリスト。 各要素はGPUShaderModuleの@group属性に対応し、N番目の要素が@group(N)に対応します。
createPipelineLayout(descriptor)-
GPUPipelineLayoutを作成します。呼び出し元:GPUDevicethis.引数:
GPUDevice.createPipelineLayout(descriptor) メソッドの引数。 パラメータ 型 Nullable Optional 説明 descriptorGPUPipelineLayoutDescriptor✘ ✘ 作成する GPUPipelineLayoutの説明。戻り値:
GPUPipelineLayout現行標準タイムライン手順:
-
plを! 新しいWebGPUオブジェクトの生成(this,
GPUPipelineLayout, descriptor)とする。 -
thisのデバイスタイムラインでinitialization stepsを発行。
-
plを返す。
デバイスタイムライン initialization steps:-
limitsをthis.
[[device]].[[limits]]とする。 -
bindGroupLayoutsを
nullのGPUBindGroupLayoutで構成されたlistとして用意し、サイズはlimits.maxBindGroupsとする。 -
各bindGroupLayout(インデックスi)についてdescriptor.
bindGroupLayouts内で:-
bindGroupLayoutが
nullでなく、かつbindGroupLayout.[[descriptor]].entriesが空でない場合:-
bindGroupLayouts[i]にbindGroupLayoutを設定。
-
-
-
非
nullなbglについて、bgl.[[descriptor]].entriesを連結した結果をallEntriesとする。 -
以下の条件が満たされない場合検証エラー生成、plの無効化、return。
-
bindGroupLayouts内の非
nullなGPUBindGroupLayoutはすべて、thisで有効利用可能であり、かつ[[exclusivePipeline]]がnullであること。 -
descriptor.
bindGroupLayoutsのサイズはlimits.maxBindGroups以下であること。 -
allEntriesがlimitsのバインディングスロット制限超過でないこと。
-
-
pl.
[[bindGroupLayouts]]にbindGroupLayoutsを設定。
-
注: 2つのGPUPipelineLayout
オブジェクトは、内部の[[bindGroupLayouts]]シーケンスが
GPUBindGroupLayoutでグループ同等であれば、いかなる用途でも等価とみなされます。
8.4. 例
GPUBindGroupLayoutを作成します。
そして、GPUBindGroupと
GPUPipelineLayout
を、このGPUBindGroupLayoutを用いて作成します。
const bindGroupLayout= gpuDevice. createBindGroupLayout({ entries: [{ binding: 0 , visibility: GPUShaderStage. VERTEX| GPUShaderStage. FRAGMENT, buffer: {} }, { binding: 1 , visibility: GPUShaderStage. FRAGMENT, texture: {} }, { binding: 2 , visibility: GPUShaderStage. FRAGMENT, sampler: {} }] }); const bindGroup= gpuDevice. createBindGroup({ layout: bindGroupLayout, entries: [{ binding: 0 , resource: { buffer: buffer}, }, { binding: 1 , resource: texture}, { binding: 2 , resource: sampler}] }); const pipelineLayout= gpuDevice. createPipelineLayout({ bindGroupLayouts: [ bindGroupLayout] });
9. シェーダーモジュール
9.1. GPUShaderModule
[Exposed =(Window ,Worker ),SecureContext ]interface GPUShaderModule {Promise <GPUCompilationInfo >getCompilationInfo (); };GPUShaderModule includes GPUObjectBase ;
GPUShaderModule
は内部シェーダーモジュールオブジェクトへの参照です。
9.1.1. シェーダーモジュールの生成
dictionary :GPUShaderModuleDescriptor GPUObjectDescriptorBase {required USVString code ;sequence <GPUShaderModuleCompilationHint >compilationHints = []; };
code, 型 USVString-
シェーダーモジュールの WGSL ソースコード。
compilationHints, 型 sequence<GPUShaderModuleCompilationHint>、デフォルト値[]-
GPUShaderModuleCompilationHintのリストです。アプリケーションが提供するヒントには、最終的にエントリーポイントから作成されるパイプラインのエントリーポイント情報を含めるべきです。
実装は、
GPUShaderModuleCompilationHintに含まれる情報を使用して、createShaderModule()内で可能な限り多くのコンパイルを行うべきです。型チェック以外では、これらのヒントは一切検証されません。
注:compilationHintsに情報を指定しても、 性能以外に観測可能な効果はありません。作成されないパイプラインに対してヒントを与えると性能が低下する場合もあります。1つのシェーダーモジュールは複数のエントリーポイントを持つことができ、複数のパイプラインが単一のシェーダーモジュールから作成されるため、 実装側は
createShaderModule()で一度にできるだけ多くのコンパイルを行うことで、複数回createComputePipeline()やcreateRenderPipeline()を呼び出すよりも高い性能を得られる場合があります。ヒントは明示的に名前が指定されたエントリーポイントにのみ適用されます。
GPUProgrammableStage.entryPointとは異なり、デフォルト値はありません(モジュールにエントリーポイントが1つだけであっても)。注: ヒントは観測可能な方法で検証されませんが、ユーザーエージェントは(未知のエントリーポイント名や非互換なパイプラインレイアウトなどの)識別可能なエラーを開発者向けに 表示してもかまいません(例: ブラウザの開発者コンソールなど)。
createShaderModule(descriptor)-
GPUShaderModuleを生成します。呼び出し元:GPUDevicethis。引数:
GPUDevice.createShaderModule(descriptor) メソッドの引数。 パラメータ 型 Nullable Optional 説明 descriptorGPUShaderModuleDescriptor✘ ✘ GPUShaderModuleの説明戻り値:
GPUShaderModuleコンテンツタイムラインの手順:
-
sm を ! 新しい WebGPU オブジェクトを作成する(this,
GPUShaderModule, descriptor)。 -
initialization steps を デバイスタイムライン上で実行する。
-
sm を返す。
デバイスタイムライン initialization steps:-
error を、WGSL ソース descriptor.
codeで シェーダーモジュール生成時に発生したエラー、またはエラーがなければnullとする。 -
以下の要件が満たされない場合、 バリデーションエラーを生成し、sm を無効化し、終了する。
注: 分類されていないエラーは シェーダーモジュールの生成時には発生しません。 実装が生成時にそのようなエラーを検出した場合、シェーダーモジュールは有効であるかのように振る舞い、パイプライン生成までエラーの提示を遅延させる必要があります。
注:ユーザーエージェントは、ここで発生するバリデーションエラーのmessageテキストに詳細なコンパイラエラーメッセージやシェーダーテキストを含めるべきではありません: これらの詳細はgetCompilationInfo()で取得できます。 ユーザーエージェントは、開発者向けに人間が読める形式のエラー詳細を表示するべきです (例: ブラウザの開発者コンソールの警告、シェーダー全文表示可能など)。シェーダーのコンパイルエラーは現行標準のアプリケーションではまれなため、ユーザーエージェントは エラー処理 (GPUエラースコープ や
uncapturederrorイベントハンドラ) に関係なく、開発者向けに表示しても良いです。 そうしない場合は、ユーザーが人間向けの詳細を必ず取得できる方法(例: チェックボックスでエラー表示、GPUCompilationInfoオブジェクトをコンソールに表示時に詳細表示など)を用意し、文書化すべきです。 -
GPUShaderModule
を作成する:
// ビューポート全体を赤で塗りつぶす単純なバーテックス・フラグメントシェーダーペア。 const shaderSource= ` var<private> pos : array<vec2<f32>, 3> = array<vec2<f32>, 3>( vec2(-1.0, -1.0), vec2(-1.0, 3.0), vec2(3.0, -1.0)); @vertex fn vertexMain(@builtin(vertex_index) vertexIndex : u32) -> @builtin(position) vec4<f32> { return vec4(pos[vertexIndex], 1.0, 1.0); } @fragment fn fragmentMain() -> @location(0) vec4<f32> { return vec4(1.0, 0.0, 0.0, 1.0); } ` ; const shaderModule= gpuDevice. createShaderModule({ code: shaderSource, });
9.1.1.1. シェーダーモジュールのコンパイルヒント
シェーダーモジュールのコンパイルヒントは、任意の追加情報であり、特定の
GPUShaderModule
エントリーポイントが将来的にどのように使用される予定かを示します。一部の実装では、この情報によってシェーダーモジュールを早期にコンパイルでき、性能向上につながる場合があります。
dictionary {GPUShaderModuleCompilationHint required USVString ; (entryPoint GPUPipelineLayout or GPUAutoLayoutMode )layout ; };
layout, 型(GPUPipelineLayout or GPUAutoLayoutMode)-
GPUPipelineLayoutは、GPUShaderModuleが今後createComputePipeline()やcreateRenderPipeline()の呼び出し時に使用される場合に参照されます。"auto"に設定した場合は、このヒントに関連付けられたエントリーポイント用のデフォルトのパイプラインレイアウトが使用されます。
createShaderModule()
と createComputePipeline()
/
createRenderPipeline()
の両方に同じ情報を渡すべきです。
アプリケーションが createShaderModule()
の呼び出し時にヒント情報を提供できない場合は、通常
createShaderModule()
の呼び出しを遅らせるのではなく、
compilationHints
配列や GPUShaderModuleCompilationHint
の個々のメンバーから未知の情報を省略するべきです。
省略した場合、コンパイルは createComputePipeline()
/
createRenderPipeline()
時に遅延して行われる可能性があります。
著者が createShaderModule()
に渡すヒント情報が、後で同じモジュールに対して
createComputePipeline()
/
createRenderPipeline()
に渡す情報と一致しない可能性がある場合は、
createShaderModule()
にはその情報を渡さないようにすべきです。
不一致の情報を createShaderModule()
に渡すと、不要なコンパイルが発生する場合があります。
9.1.2. シェーダーモジュールのコンパイル情報
enum {GPUCompilationMessageType ,"error" ,"warning" , }; ["info" Exposed =(Window ,Worker ),Serializable ,SecureContext ]interface {GPUCompilationMessage readonly attribute DOMString message ;readonly attribute GPUCompilationMessageType type ;readonly attribute unsigned long long lineNum ;readonly attribute unsigned long long linePos ;readonly attribute unsigned long long offset ;readonly attribute unsigned long long length ; }; [Exposed =(Window ,Worker ),Serializable ,SecureContext ]interface {GPUCompilationInfo readonly attribute FrozenArray <GPUCompilationMessage >; };messages
GPUCompilationMessage
は、GPUShaderModule
のコンパイラによって生成される情報メッセージ、警告、またはエラーメッセージです。これらのメッセージは人間が読める形で提供され、開発者がシェーダー code
の問題を診断しやすくなっています。
各メッセージは、シェーダーコード内の単一の位置、コードの部分文字列、またはコードの特定の位置に対応しない場合もあります。
GPUCompilationMessage
には以下の属性があります:
message, 型 DOMString, 読み取り専用-
このコンパイルメッセージの人間が読めるローカライズ可能なテキスト。
注:
messageは言語および方向情報のベストプラクティスに従うべきです。これには、今後登場する文字列の言語・方向メタデータに関する標準を活用することも含みます。編集上の注: 本書執筆時点では、レガシーAPIと互換性・一貫性を持つ言語/方向の推奨事項はありませんが、今後登場した際は正式に採用してください。
type, 型 GPUCompilationMessageType, 読み取り専用-
メッセージの重大度レベル。
typeが"error"の場合、 シェーダー生成エラーに対応します。 lineNum, 型 unsigned long long, 読み取り専用-
この
messageが対応するシェーダーcodeの行番号。値は1始まりで、1はシェーダーcodeの最初の行を示します。 行区切りは改行です。messageが部分文字列に対応する場合は、その部分文字列が始まる行を指します。メッセージがシェーダーcodeの特定の位置に対応しない場合は、値は0です。 linePos, 型 unsigned long long, 読み取り専用-
シェーダー
lineNum行の先頭から、messageが対応する位置/部分文字列のUTF-16コード単位数。値は1始まりで、linePosが1の場合はその行の最初のコードユニットです。messageが部分文字列に対応する場合は、その部分文字列の最初のUTF-16コードユニットを指します。メッセージがシェーダーcodeの特定の位置に対応しない場合は、値は0です。 offset, 型 unsigned long long, 読み取り専用-
シェーダー
codeの先頭から、messageが対応する位置/部分文字列までのUTF-16コード単位数。同じ位置はlineNumおよびlinePosでも参照されます。メッセージがシェーダーcodeの特定の位置に対応しない場合は、値は0です。 length, 型 unsigned long long, 読み取り専用-
messageが対応する部分文字列のUTF-16コード単位数。メッセージが部分文字列に対応しない場合はlengthは0です。
注: GPUCompilationMessage.lineNum
および
GPUCompilationMessage.linePos
は、主な用途が多くのテキストエディタの行・列番号と照合できる人間向けメッセージの印刷であるため、1始まりです。
注: GPUCompilationMessage.offset
および
GPUCompilationMessage.length
は、シェーダー code
の部分文字列取得に substr() へ渡すのに適しています。
message
が対応する部分文字列を抽出できます。
getCompilationInfo()-
GPUShaderModuleの コンパイル時に生成されたメッセージを返します。メッセージの位置、順序、内容は実装依存です。 特に、メッセージは
lineNumでソートされているとは限りません。呼び出し元:GPUShaderModulethis戻り値:
Promise<GPUCompilationInfo>コンテンツタイムラインの手順:
-
現在の コンテンツタイムライン を contentTimeline とする。
-
promise を新しい Promiseとして生成する。
-
synchronization steps を デバイスタイムライン上で実行する。
-
promise を返す。
デバイスタイムライン synchronization steps:-
this の シェーダーモジュール生成が(成功・失敗問わず)完了したときに event が発生する。
-
タイムラインイベントを監視 event を this.
[[device]]で発生させ、以降の手順は contentTimeline で処理する。
コンテンツタイムラインの手順:-
新しい
GPUCompilationInfoを info とする。 -
シェーダーモジュール生成時に this で生成されたエラー・警告・情報メッセージのリストを messages とする。デバイスが失われた場合は空リスト
[]。 -
messages の各 message について:
-
新しい
GPUCompilationMessageを m とする。 -
m.
messageに message のテキストを設定する。 -
- message がシェーダー
code内の特定の部分文字列や位置に対応する場合: - その他:
- message がシェーダー
-
-
promise を info で解決する。
-
10. パイプライン
パイプラインは、GPUComputePipeline
や GPURenderPipeline
のいずれであっても、バインディングや頂点バッファなどの入力データを処理して、出力レンダーターゲットの色などの出力を生成する、GPUハードウェア・ドライバー・ユーザーエージェントの組み合わせによる機能全体を表します。
構造的には、パイプラインはプログラム可能なステージ(シェーダー)と、ブレンドモードなどの固定機能ステートの連なりで構成されます。
注: 内部的には、ターゲットプラットフォームによっては、ドライバーが一部の固定機能ステートをシェーダーコードに変換し、ユーザーが提供したシェーダーとリンクする場合があります。このリンク処理が、オブジェクトを一体として生成する理由のひとつです。
この組み合わせ状態は1つのオブジェクト
(GPUComputePipeline
または GPURenderPipeline)
として作成され、1つのコマンド
(GPUComputePassEncoder.setPipeline()
または
GPURenderCommandsMixin.setPipeline()
で切り替えます。
パイプラインの生成方法は2つあります:
- 即時パイプライン生成
-
createComputePipeline()およびcreateRenderPipeline()は、パスエンコーダで即座に使用可能なパイプラインオブジェクトを返します。これが失敗すると、パイプラインオブジェクトは無効となり、呼び出しは バリデーションエラーまたは内部エラーを生成します。
注: ハンドルオブジェクトは即座に返されますが、実際のパイプライン生成は同期的ではありません。 パイプライン生成に時間がかかる場合、生成呼び出しからパイプラインが最初に使用される
submit()実行までの間の デバイスタイムライン のどこかで待ちが発生する可能性があります。 このタイミングは規定されていませんが、主に次のいずれかです: 生成時、setPipeline()でパイプラインが初めて使われる時、対応するfinish()(GPUCommandEncoderまたはGPURenderBundleEncoder)時、 またはsubmit()でGPUCommandBufferが実行された時です。 - 非同期 パイプライン生成
-
createComputePipelineAsync()およびcreateRenderPipelineAsync()は、パイプライン生成が完了するとパイプラインオブジェクトに解決されるPromiseを返します。失敗した場合、
PromiseはGPUPipelineErrorで reject されます。
GPUPipelineErrorはパイプライン生成失敗を表します。
[Exposed =(Window ,Worker ),SecureContext ,Serializable ]interface GPUPipelineError :DOMException {constructor (optional DOMString message = "",GPUPipelineErrorInit options );readonly attribute GPUPipelineErrorReason reason ; };dictionary {GPUPipelineErrorInit required GPUPipelineErrorReason ; };reason enum GPUPipelineErrorReason {"validation" ,"internal" , };
GPUPipelineError
のコンストラクタ:
constructor()-
引数:
GPUPipelineError.constructor() メソッドの引数。 パラメータ 型 Nullable Optional 説明 messageDOMString✘ ✔ 基底 DOMExceptionのエラーメッセージoptionsGPUPipelineErrorInit✘ ✘ GPUPipelineError固有のオプションコンテンツタイムラインの手順:
GPUPipelineError
には以下の属性があります:
reason, 型 GPUPipelineErrorReason, 読み取り専用-
パイプライン生成時に遭遇したエラー種別を
GPUPipelineErrorReasonとして公開する読み取り専用スロット属性です:-
"validation": バリデーションエラー -
"internal": 内部エラー
-
GPUPipelineError
オブジェクトはシリアライズ可能オブジェクトです。
-
DOMExceptionのシリアライズ手順を value と serialized に対して実行する。
-
DOMExceptionのデシリアライズ手順を value と serialized に対して実行する。
10.1. ベースパイプライン
enum {GPUAutoLayoutMode , };"auto" dictionary :GPUPipelineDescriptorBase GPUObjectDescriptorBase {required (GPUPipelineLayout or GPUAutoLayoutMode )layout ; };
layout, 型(GPUPipelineLayout or GPUAutoLayoutMode)-
このパイプラインの
GPUPipelineLayoutまたは"auto"を指定すると パイプラインレイアウトが自動生成されます。注:
"auto"を使用した場合、そのパイプラインは他のパイプラインとGPUBindGroupを共有できません。
interface mixin { [GPUPipelineBase NewObject ]GPUBindGroupLayout getBindGroupLayout (unsigned long index ); };
GPUPipelineBase
には以下のデバイスタイムラインプロパティがあります:
[[layout]], 型GPUPipelineLayout-
thisで使用できるリソースのレイアウト定義。
GPUPipelineBase
には以下のメソッドがあります:
getBindGroupLayout(index)-
GPUPipelineBaseのGPUBindGroupLayoutに互換性のあるGPUBindGroupLayoutをindexで取得します。呼び出し元:GPUPipelineBasethis引数:
GPUPipelineBase.getBindGroupLayout(index) メソッドの引数。 パラメータ 型 Nullable Optional 説明 indexunsigned long✘ ✘ パイプラインレイアウトの [[bindGroupLayouts]]シーケンスのインデックス。戻り値:
GPUBindGroupLayoutコンテンツタイムラインの手順:
-
新しい
GPUBindGroupLayoutオブジェクトを layout とする。 -
this の デバイスタイムライン上で initialization steps を実行する。
-
layout を返す。
デバイスタイムライン initialization steps:-
limits を this.
[[device]].[[limits]]とする。 -
以下のいずれかの条件が満たされない場合 バリデーションエラーを生成し、layoutを無効化して終了する。
-
this は 有効であること。
-
index < limits.
maxBindGroupsであること。
-
-
layout を this.
[[layout]].[[bindGroupLayouts]][index] のコピーとして初期化する。注:
GPUBindGroupLayoutは常に値渡しで使われ、参照渡しにはなりません。 つまり、同じ内部オブジェクトを新しいWebGPUインターフェースで返すのと同じです。 毎回新しいGPUBindGroupLayoutWebGPUインターフェースが返されるので、 コンテンツタイムラインとデバイスタイムライン間の往復を避けることができます。
-
10.1.1. デフォルトパイプラインレイアウト
GPUPipelineBase
オブジェクトが layout
に
"auto"
を設定して作成された場合、デフォルトレイアウトが生成されて使用されます。
注: デフォルトレイアウトは簡単なパイプライン向けの便宜で提供されていますが、ほとんどの場合は明示的なレイアウトの利用が推奨されます。デフォルトレイアウトで作成したバインドグループは他のパイプラインと共有できず、シェーダーを変更するとデフォルトレイアウトの構造も変化し、予期しないバインドグループ生成エラーが発生することがあります。
デフォルトパイプラインレイアウトを GPUPipelineBase
pipeline に対して生成するには、
以下のデバイスタイムライン手順を実行する:
-
groupCount を 0 にする。
-
groupDescs を device.
[[limits]].maxBindGroups個の新しいGPUBindGroupLayoutDescriptorオブジェクトの配列とする。 -
groupDescs の各 groupDesc について:
-
pipeline を生成したディスクリプタ内の各
GPUProgrammableStagestageDesc について:-
shaderStage を stageDesc が pipeline で使用されるシェーダーステージの
GPUShaderStageFlagsとする。 -
entryPoint を get the entry point(shaderStage, stageDesc) とする。Assert entryPoint は
nullではない。 -
entryPoint が 静的に使用する各 resource resource について:
-
group を resource の "group" 修飾子とする。
-
binding を resource の "binding" 修飾子とする。
-
entry を新しい
GPUBindGroupLayoutEntryとする。 -
entry.
bindingに bindingを設定する。 -
entry.
visibilityに shaderStage を設定する。 -
resource がサンプラーバインディングの場合:
-
samplerLayout を新しい
GPUSamplerBindingLayoutとする。 -
entry.
samplerに samplerLayout を設定する。
-
-
resource が比較サンプラーバインディングの場合:
-
samplerLayout を新しい
GPUSamplerBindingLayoutとする。 -
samplerLayout.
typeに"comparison"を設定する。 -
entry.
samplerに samplerLayout を設定する。
-
-
resource がバッファバインディングの場合:
-
bufferLayout を新しい
GPUBufferBindingLayoutとする。 -
bufferLayout.
minBindingSizeに resource の最小バッファバインディングサイズを設定する。 -
resource が読み取り専用ストレージバッファの場合:
-
bufferLayout.
typeに"read-only-storage"を設定する。
-
-
resource がストレージバッファの場合:
-
entry.
bufferに bufferLayout を設定する。
-
-
resource がサンプリングテクスチャバインディングの場合:
-
textureLayout を新しい
GPUTextureBindingLayoutとする。 -
resource が深度テクスチャバインディングの場合:
-
textureLayout.
sampleTypeに"depth"を設定する。
そうでない場合、resource のサンプル型が:
f32かつ stageDesc から resource へのサンプラー付きテクスチャ組み込み関数呼び出しが 静的に使用されている場合-
textureLayout.
sampleTypeに"float"を設定する。 f32その他の場合-
textureLayout.
sampleTypeに"unfilterable-float"を設定する。 i32-
textureLayout.
sampleTypeに"sint"を設定する。 u32-
textureLayout.
sampleTypeに"uint"を設定する。
-
-
textureLayout.
viewDimensionに resource の次元を設定する。 -
resource がマルチサンプルテクスチャの場合:
-
textureLayout.
multisampledにtrueを設定する。
-
-
entry.
textureに textureLayout を設定する。
-
-
resource がストレージテクスチャバインディングの場合:
-
storageTextureLayout を新しい
GPUStorageTextureBindingLayoutとする。 -
storageTextureLayout.
formatに resource のフォーマットを設定する。 -
storageTextureLayout.
viewDimensionに resource の次元を設定する。 -
アクセスモードが:
read-
textureLayout.
accessに"read-only"を設定する。 write-
textureLayout.
accessに"write-only"を設定する。 read_write-
textureLayout.
accessに"read-write"を設定する。
-
entry.
storageTextureに storageTextureLayout を設定する。
-
-
groupCount を max(groupCount, group + 1) にする。
-
groupDescs[group] に
bindingが binding と等しい entry previousEntry がある場合:-
entry の
visibilityが previousEntry と異なる場合:-
entry.
visibilityでセットされたビットを previousEntry.visibilityに追加する。
-
-
resource がバッファバインディングで、entry の
buffer.minBindingSizeが previousEntry より大きい場合:-
previousEntry.
buffer.minBindingSizeに entry.buffer.minBindingSizeを設定する。
-
-
resource がサンプリングテクスチャバインディングで、entry の
texture.sampleTypeが previousEntry と異なり、かつ両方ともsampleTypeが"float"または"unfilterable-float"の場合:-
previousEntry.
texture.sampleTypeに"float"を設定する。
-
-
その他のプロパティが entry と previousEntry の間で異なる場合:
-
nullを返す(パイプライン生成は失敗する)。
-
-
resource がストレージテクスチャバインディングで、 entry.storageTexture.
accessが"read-write"、 previousEntry.storageTexture.accessが"write-only"、 かつ previousEntry.storageTexture.formatが § 26.1.1 プレーンカラー形式テーブルに従ってSTORAGE_BINDINGと"read-write"に互換性がある場合:-
previousEntry.storageTexture.
accessに"read-write"を設定する。
-
-
-
それ以外の場合
-
entry を groupDescs[group] に追加する。
-
-
-
-
groupLayouts を新しいリストとする。
-
i を 0 から groupCount - 1 まで順に:
-
groupDesc を groupDescs[i] とする。
-
bindGroupLayout を device.
createBindGroupLayout()(groupDesc) の結果とする。 -
bindGroupLayout.
[[exclusivePipeline]]に pipeline を設定する。 -
bindGroupLayout を groupLayouts に追加する。
-
-
desc を新しい
GPUPipelineLayoutDescriptorとする。 -
desc.
bindGroupLayoutsに groupLayouts を設定する。 -
device.
createPipelineLayout()(desc) を返す。
10.1.2. GPUProgrammableStage
GPUProgrammableStage
は、ユーザーが提供した
GPUShaderModule
内でパイプラインのプログラム可能ステージの1つを制御するエントリーポイントを記述します。
エントリーポイント名はWGSL識別子比較で定義された規則に従います。
dictionary GPUProgrammableStage {required GPUShaderModule module ;USVString entryPoint ;record <USVString ,GPUPipelineConstantValue >constants = {}; };typedef double GPUPipelineConstantValue ; // WGSLのbool, f32, i32, u32, および有効ならf16を表す場合がある。
GPUProgrammableStage
には以下のメンバーがあります:
module, 型 GPUShaderModule-
このプログラム可能ステージが実行するコードを含む
GPUShaderModuleです。 entryPoint, 型 USVString-
module内でこのステージが処理を行う関数名。注:
entryPointは必須ではないため、GPUProgrammableStageを受け取るメソッドは "get the entry point"アルゴリズムを使って どのエントリーポイントを指しているか決定しなければなりません。 constants, 型 record<USVString, GPUPipelineConstantValue>, デフォルト値{}-
シェーダーモジュール
module内の パイプラインオーバーライド可能定数の値を指定します。各パイプラインオーバーライド可能定数は、 1つの パイプラインオーバーライド定数識別子文字列で一意に識別されます。宣言でIDが指定されている場合はパイプライン定数ID、そうでなければ定数の識別子名です。
各キーバリューペアのキーは、 識別子文字列と一致しなければならず、 比較はWGSL識別子比較の規則に従います。 パイプライン実行時、その定数は指定された値を持ちます。
値は
GPUPipelineConstantValue(double)として指定されます。 WGSL型へ変換され、 定数の型がbool/i32/u32/f32/f16のいずれかになります。 変換に失敗した場合はバリデーションエラーが生成されます。WGSLで定義されたパイプラインオーバーライド可能定数:@id ( 0 ) override has_point_light : bool= true ; // アルゴリズム制御用。 @id ( 1200 ) override specular_param : f32= 2.3 ; // 数値制御。 @id ( 1300 ) override gain : f32; // 必ずオーバーライドされる必要あり。 override width : f32= 0.0 ; // APIレベルで指定 // 名前 "width" を使う。 override depth : f32; // APIレベルで指定 // 名前 "depth"。 // 必ずオーバーライドされる必要あり。 override height = 2 * depth ; // デフォルト値 // (APIレベルでセットされてなければ)、 // 他のオーバーライド可能定数に依存。 対応するJavaScriptコード、必須オーバーライドのみ提供:
{ // ... constants: { 1300 : 2.0 , // "gain" depth: - 1 , // "depth" } } 全ての定数をオーバーライドする場合のJavaScriptコード:
{ // ... constants: { 0 : false , // "has_point_light" 1200 : 3.0 , // "specular_param" 1300 : 2.0 , // "gain" width: 20 , // "width" depth: - 1 , // "depth" height: 15 , // "height" } }
GPUShaderStage
stage,
GPUProgrammableStage
descriptor) のデバイスタイムライン手順:
-
descriptor.
entryPointが指定されている場合:-
descriptor.
moduleに、 名前が descriptor.entryPointと一致し、 シェーダーステージが stage と一致するエントリーポイントが含まれているなら、 そのエントリーポイントを返す。そうでなければ
nullを返す。
そうでない場合:
-
descriptor.
module内で、シェーダーステージが stage と一致するエントリーポイントがちょうど1つだけある場合、そのエントリーポイントを返す。そうでなければ
nullを返す。
-
引数:
-
GPUShaderStagestage -
GPUProgrammableStagedescriptor -
GPUPipelineLayoutlayout -
GPUDevicedevice
以下の手順のすべての要件が満たされていなければならない。
どれかが満たされない場合はfalseを返し、すべて満たされていればtrueを返す。
-
entryPoint を get the entry point(stage, descriptor) とする。
-
entryPoint は
nullであってはならない。 -
entryPoint が静的に使用する各bindingについて:
-
validating shader binding(binding, layout)が
trueを返さなければならない。
-
-
entryPointをルートとするシェーダーステージ内の関数における各テクスチャ組み込み関数呼び出しについて、 それが sampled texture型またはdepth texture型のtextureBindingと
sampler型(sampler_comparisonを除く)のsamplerBindingを使う場合:-
texture を textureBindingに対応する
GPUBindGroupLayoutEntryとする。 -
sampler を samplerBindingに対応する
GPUBindGroupLayoutEntryとする。 -
もし sampler.
typeが"filtering"なら、 texture.sampleTypeは"float"でなければならない。
注:
"comparison"サンプラーは"depth"テクスチャにのみ使用可能です。これはWGSLのtexture_depth_*バインディングにバインドできる唯一のテクスチャ型です。 -
-
descriptor.
constants内の各key → valueについて:-
keyはパイプラインオーバーライド定数識別子文字列 と一致しなければならず、 その定数はシェーダーモジュールdescriptor.
module内でパイプラインオーバーライド可能定数として定義されていなければならない。 比較はWGSL識別子比較の規則に従う。 この定数がentryPointに静的に使用されている必要はない。 型をTとする。
-
-
entryPointがパイプラインオーバーライド定数識別子文字列 keyを静的に使用している場合、
-
その定数がデフォルト値を持たない場合は、 descriptor.
constantsにkeyが含まれていなければならない。
-
引数:
-
シェーダーバインディング宣言 variable(シェーダーモジュールから反映されたモジュールスコープ変数宣言)
-
GPUPipelineLayoutlayout
bindGroup をシェーダーバインディング宣言 variable のバインドグループインデックス、 bindIndex をバインディングインデックスとする。
以下すべての条件を満たせばtrueを返す:
-
layout.
[[bindGroupLayouts]][bindGroup] がGPUBindGroupLayoutEntryentry を含み、entry.binding== bindIndexであること。 -
定義済みのentryのbinding memberが:
buffer-
"uniform"-
variable はアドレス空間
uniformで宣言されている。 "storage"-
variable はアドレス空間
storageかつアクセスモードread_writeで宣言されている。 "read-only-storage"-
variable はアドレス空間
storageかつアクセスモードreadで宣言されている。
もしentry.
buffer.minBindingSizeが0でない場合、 それは関連するシェーダー内のバッファバインディング変数の最小バッファバインディングサイズ以上でなければならない。 sampler-
"filtering"または"non-filtering"-
variable の型は
sampler。 "comparison"-
variable の型は
sampler_comparison。
texture-
entry.
texture.multisampledがtrueなら、variable の型はtexture_multisampled_2d<T>またはtexture_depth_multisampled_2d<T>。entry.
texture.sampleTypeが:"float","unfilterable-float","sint"または"uint"-
variable の型は以下のいずれか:
-
texture_1d<T> -
texture_2d<T> -
texture_2d_array<T> -
texture_cube<T> -
texture_cube_array<T> -
texture_3d<T> -
texture_multisampled_2d<T>
entry.
texture.sampleTypeが:"float"または"unfilterable-float"-
サンプル型
Tはf32。 "sint"-
サンプル型
Tはi32。 "uint"-
サンプル型
Tはu32。
-
"depth"-
variable の型は以下のいずれか:
-
texture_2d<T> -
texture_2d_array<T> -
texture_cube<T> -
texture_cube_array<T> -
texture_multisampled_2d<T> -
texture_depth_2d -
texture_depth_2d_array -
texture_depth_cube -
texture_depth_cube_array -
texture_depth_multisampled_2d
サンプル型
Tはf32。 -
entry.
texture.viewDimensionが:"1d"-
variable の型は
texture_1d<T>。 "2d"-
variable の型は
texture_2d<T>またはtexture_multisampled_2d<T>。 "2d-array"-
variable の型は
texture_2d_array<T>。 "cube"-
variable の型は
texture_cube<T>。 "cube-array"-
variable の型は
texture_cube_array<T>。 "3d"-
variable の型は
texture_3d<T>。
storageTexture-
entry.
storageTexture.viewDimensionが:"1d"-
variable の型は
texture_storage_1d<T, A>。 "2d"-
variable の型は
texture_storage_2d<T, A>。 "2d-array"-
variable の型は
texture_storage_2d_array<T, A>。 "3d"-
variable の型は
texture_storage_3d<T, A>。
entry.
storageTexture.accessが:"write-only"-
アクセスモード
Aはwrite。 "read-only"-
アクセスモード
Aはread。 "read-write"-
アクセスモード
Aはread_writeまたはwrite。
テクセルフォーマット
Tは entry.storageTexture.formatと一致する。
-
T を store型(格納型)とする。
-
もし T がランタイムサイズ配列、またはランタイムサイズ配列を含む場合、 その
array<E>をarray<E, 1>に置き換える。注: これにより常に1要素分のメモリが確保され、配列インデックスを配列長にクランプすることで、メモリ内アクセスが保証されます。
-
SizeOf(T) を返す。
注: この下限を強制することで、バッファ変数による読み書きはバッファの境界領域内のメモリだけにアクセスすることが保証されます。
10.2. GPUComputePipeline
GPUComputePipeline
は、コンピュートシェーダーステージを制御し、
パイプラインの一種であり、
GPUComputePassEncoder
で使用できます。
コンピュートの入力・出力はすべてバインディングに格納され、
指定された GPUPipelineLayout
に従います。
出力は buffer
バインディング(型が "storage")
や storageTexture
バインディング(型が
"write-only"
または
"read-write")
に対応します。
コンピュートパイプラインのステージ:
-
コンピュートシェーダー
[Exposed =(Window ,Worker ),SecureContext ]interface GPUComputePipeline { };GPUComputePipeline includes GPUObjectBase ;GPUComputePipeline includes GPUPipelineBase ;
10.2.1. コンピュートパイプラインの生成
GPUComputePipelineDescriptor
はコンピュートパイプラインを記述します。詳細は
§ 23.1 計算処理を参照してください。
dictionary :GPUComputePipelineDescriptor GPUPipelineDescriptorBase {required GPUProgrammableStage compute ; };
GPUComputePipelineDescriptor
には以下のメンバーがあります:
compute, 型 GPUProgrammableStage-
パイプラインのコンピュートシェーダーのエントリーポイントを記述します。
createComputePipeline(descriptor)-
即時パイプライン生成で
GPUComputePipelineを作成します。呼び出し元:GPUDevicethis.引数:
GPUDevice.createComputePipeline(descriptor) メソッドの引数。 パラメータ 型 Nullable Optional 説明 descriptorGPUComputePipelineDescriptor✘ ✘ 作成する GPUComputePipelineの説明。戻り値:
GPUComputePipelineコンテンツタイムラインの手順:
-
pipeline を ! 新しいWebGPUオブジェクトの作成(this,
GPUComputePipeline, descriptor) とする。 -
initialization steps を デバイスタイムライン上で実行する。
-
pipeline を返す。
デバイスタイムライン initialization steps:-
layout を descriptor.
layoutが"auto"なら デフォルトパイプラインレイアウトの新規生成結果、 そうでなければ descriptor.layoutとする。 -
以下のすべての要件が満たされていなければならない。 どれかが満たされない場合はバリデーションエラーを生成し、pipelineを無効化して終了する。
-
layout は thisに対して有効でなければならない。
-
GPUProgrammableStageの検証(
COMPUTE, descriptor.compute, layout, this) が成功しなければならない。 -
entryPoint を get the entry point(
COMPUTE, descriptor.compute) とする。Assert entryPoint は
nullであってはならない。 -
workgroupStorageUsed を entryPoint がworkgroupアドレス空間を持ち 静的に使用されるすべての型 T について、 roundUp(16, SizeOf(T)) の合計とする。
workgroupStorageUsed は device.limits.
maxComputeWorkgroupStorageSize以下でなければならない。 -
entryPoint は device.limits.
maxComputeInvocationsPerWorkgroup以下のinvocation数でなければならない。 -
entryPoint の
workgroup_size属性の各成分は、 [device.limits.maxComputeWorkgroupSizeX, device.limits.maxComputeWorkgroupSizeY, device.limits.maxComputeWorkgroupSizeZ] の対応する成分以下でなければならない。
-
-
パイプライン生成の実装により パイプライン生成 未分類エラーが発生した場合は、 内部エラーを生成し、pipelineを無効化して終了する。
注: 実装がシェーダーモジュール生成時に未分類エラーを検出した場合でも、 エラーはここで通知されます。
-
pipeline.
[[layout]]に layout を設定する。
-
createComputePipelineAsync(descriptor)-
非同期パイプライン生成で
GPUComputePipelineを作成します。 返されるPromiseは、作成されたパイプラインが追加の待機なしで使用可能になったときに解決されます。パイプライン生成が失敗した場合、返される
PromiseはGPUPipelineErrorで reject されます。 (GPUErrorはデバイスにdispatchされません。)注: このメソッドは、可能な限り利用するのが推奨されます。パイプラインのコンパイルによる キュータイムライン のブロックを防ぐためです。
呼び出し元:GPUDevicethis.引数:
GPUDevice.createComputePipelineAsync(descriptor) メソッドの引数。 パラメータ 型 Nullable Optional 説明 descriptorGPUComputePipelineDescriptor✘ ✘ 作成する GPUComputePipelineの説明。戻り値:
Promise<GPUComputePipeline>コンテンツタイムラインの手順:
-
現在の コンテンツタイムライン を contentTimeline とする。
-
promise を新しいPromiseとして生成する。
-
initialization steps を デバイスタイムライン上で実行する。
-
promise を返す。
デバイスタイムライン initialization steps:-
pipeline を新しい
GPUComputePipelineとし、this.createComputePipeline()を descriptor で呼び出した場合と同様に生成し、ただしエラーはdeviceにdispatchするのではなくerrorとして捕捉する。 -
pipelineの パイプライン生成 (成功・失敗問わず)完了時に event が発生する。
-
タイムラインイベントを監視 event を this.
[[device]]で発生させ、以降の手順は デバイスタイムライン上で処理する。
デバイスタイムラインの手順:-
pipeline が 有効 または this が 失われている場合:
-
以下の手順を contentTimeline 上で実行:
コンテンツタイムラインの手順:-
promise を pipeline で解決する。
-
-
終了。
注: 失われたデバイスからはエラーは生成されません。 § 22 エラーとデバッグ参照。
-
-
pipeline が 無効 かつ error が 内部エラーの場合は、以下の手順を contentTimeline 上で実行して終了。
コンテンツタイムラインの手順:-
promise を
GPUPipelineErrorのreasonとして"internal"で reject する。
-
-
pipeline が 無効 かつ error が バリデーションエラーの場合は、以下の手順を contentTimeline 上で実行して終了。
コンテンツタイムラインの手順:-
promise を
GPUPipelineErrorのreasonとして"validation"で reject する。
-
-
GPUComputePipeline
の作成例:
const computePipeline= gpuDevice. createComputePipeline({ layout: pipelineLayout, compute: { module: computeShaderModule, entryPoint: 'computeMain' , } });
10.3. GPURenderPipeline
GPURenderPipeline
はパイプラインの一種であり、
バーテックス・フラグメントシェーダーステージを制御します。
GPURenderPassEncoder
や GPURenderBundleEncoder
で使用できます。
レンダーパイプラインの入力:
-
指定された
GPUPipelineLayoutに従うバインディング -
GPUVertexStateで記述される頂点・インデックスバッファ -
GPUColorTargetStateで記述されるカラ―アタッチメント -
任意で、
GPUDepthStencilStateで記述されるデプスステンシルアタッチメント
レンダーパイプラインの出力:
-
storageTextureバインディング(accessが"write-only"または"read-write") -
GPUColorTargetStateで記述されるカラ―アタッチメント -
任意で、
GPUDepthStencilStateで記述されるデプスステンシルアタッチメント
レンダーパイプラインは以下のレンダーステージから構成されます:
-
頂点フェッチ(
GPUVertexState.buffersで制御) -
バーテックスシェーダー(
GPUVertexStateで制御) -
プリミティブアセンブリ(
GPUPrimitiveStateで制御) -
ラスタライズ(
GPUPrimitiveState、GPUDepthStencilState、GPUMultisampleStateで制御) -
フラグメントシェーダー(
GPUFragmentStateで制御) -
ステンシルテスト・操作(
GPUDepthStencilStateで制御) -
デプステスト・書き込み(
GPUDepthStencilStateで制御) -
出力マージ(
GPUFragmentState.targetsで制御)
[Exposed =(Window ,Worker ),SecureContext ]interface GPURenderPipeline { };GPURenderPipeline includes GPUObjectBase ;GPURenderPipeline includes GPUPipelineBase ;
GPURenderPipeline
には以下のデバイスタイムラインプロパティがあります:
[[descriptor]], 型GPURenderPipelineDescriptor, 読み取り専用-
このパイプラインを記述する
GPURenderPipelineDescriptor。GPURenderPipelineDescriptorのすべてのオプションフィールドが定義されています。 [[writesDepth]], 型boolean, 読み取り専用-
パイプラインがデプス/ステンシルアタッチメントのデプス成分に書き込む場合はtrue
[[writesStencil]], 型boolean, 読み取り専用-
パイプラインがデプス/ステンシルアタッチメントのステンシル成分に書き込む場合はtrue
GPURenderPipelineDescriptor
には以下のメンバーがあります:
vertex, 型 GPUVertexState-
パイプラインのバーテックスシェーダーのエントリーポイントと、その入力バッファレイアウトを記述します。
primitive, 型 GPUPrimitiveState、デフォルト値{}-
パイプラインのプリミティブ関連プロパティを記述します。
depthStencil, 型 GPUDepthStencilState-
オプションのデプスステンシルプロパティ(テスト・操作・バイアス)を記述します。
multisample, 型 GPUMultisampleState、デフォルト値{}-
パイプラインのマルチサンプリングプロパティを記述します。
fragment, 型 GPUFragmentState-
パイプラインのフラグメントシェーダーのエントリーポイントと、その出力カラ―を記述します。指定されていない場合は、§ 23.2.8 カラー出力なしモードとなります。
createRenderPipeline(descriptor)-
即時パイプライン生成で
GPURenderPipelineを作成します。呼び出し元:GPUDevicethis.引数:
GPUDevice.createRenderPipeline(descriptor) メソッドの引数。 パラメータ 型 Nullable Optional 説明 descriptorGPURenderPipelineDescriptor✘ ✘ 作成する GPURenderPipelineの説明。戻り値:
GPURenderPipelineコンテンツタイムラインの手順:
-
descriptor.
fragmentが指定されている場合:-
各非
nullcolorStateについて descriptor.fragment.targets:-
? テクスチャフォーマット必須機能の検証を colorState.
formatと this.[[device]]で行う。
-
-
-
descriptor.
depthStencilが指定されている場合:-
? テクスチャフォーマット必須機能の検証を descriptor.
depthStencil.formatと this.[[device]]で行う。
-
-
pipeline を ! 新しいWebGPUオブジェクトの作成(this,
GPURenderPipeline, descriptor) とする。 -
initialization steps を デバイスタイムライン上で実行する。
-
pipeline を返す。
デバイスタイムライン initialization steps:-
layout を descriptor.
layoutが"auto"なら デフォルトパイプラインレイアウトの新規生成結果、 そうでなければ descriptor.layoutとする。 -
以下すべての要件が満たされていなければならない。 どれかが満たされない場合はバリデーションエラーを生成し、pipelineを無効化して終了する。
-
layout は thisに対して有効でなければならない。
-
GPURenderPipelineDescriptorの検証(descriptor, layout, this) が成功しなければならない。
-
vertexBufferCount を descriptor.
vertex.buffersの最後の非nullエントリのインデックス+1(なければ0)とする。 -
layout.
[[bindGroupLayouts]].size+vertexBufferCount は this.[[device]].[[limits]].maxBindGroupsPlusVertexBuffers以下でなければならない。
-
-
パイプライン生成の実装により パイプライン生成 未分類エラーが発生した場合は、 内部エラーを生成し、pipelineを無効化して終了する。
注: 実装がシェーダーモジュール生成時に未分類エラーを検出した場合でも、 エラーはここで通知されます。
-
pipeline.
[[descriptor]]に descriptor を設定する。 -
pipeline.
[[writesDepth]]に false を設定する。 -
pipeline.
[[writesStencil]]に false を設定する。 -
depthStencil を descriptor.
depthStencilとする。 -
depthStencil が null でない場合:
-
depthStencil.
depthWriteEnabledが指定されている場合:-
pipeline.
[[writesDepth]]に depthStencil.depthWriteEnabledを設定する。
-
-
depthStencil.
stencilWriteMaskが 0 でない場合:-
stencilFront を depthStencil.
stencilFrontとする。 -
stencilBack を depthStencil.
stencilBackとする。 -
cullMode が
"front"でない場合、 stencilFront.passOp、 stencilFront.depthFailOp、 stencilFront.failOpのいずれかが"keep"でない場合:-
pipeline.
[[writesStencil]]に true を設定する。
-
-
cullMode が
"back"でない場合、 stencilBack.passOp、 stencilBack.depthFailOp、 stencilBack.failOpのいずれかが"keep"でない場合:-
pipeline.
[[writesStencil]]に true を設定する。
-
-
-
-
pipeline.
[[layout]]に layout を設定する。
-
createRenderPipelineAsync(descriptor)-
非同期パイプライン生成で
GPURenderPipelineを作成します。 返されるPromiseは、作成されたパイプラインが追加の待機なしで使用可能になったときに解決されます。パイプライン生成が失敗した場合、返される
PromiseはGPUPipelineErrorで reject されます。 (GPUErrorはデバイスにdispatchされません。)注: このメソッドは、可能な限り利用するのが推奨されます。パイプラインのコンパイルによる キュータイムライン のブロックを防ぐためです。
呼び出し元:GPUDevicethis.引数:
GPUDevice.createRenderPipelineAsync(descriptor) メソッドの引数。 パラメータ 型 Nullable Optional 説明 descriptorGPURenderPipelineDescriptor✘ ✘ 作成する GPURenderPipelineの説明。戻り値:
Promise<GPURenderPipeline>コンテンツタイムラインの手順:
-
現在の コンテンツタイムライン を contentTimeline とする。
-
promise を新しいPromiseとして生成する。
-
initialization steps を デバイスタイムライン上で実行する。
-
promise を返す。
デバイスタイムラインの手順:-
pipeline を新しい
GPURenderPipelineとし、this.createRenderPipeline()を descriptor で呼び出した場合と同様に生成し、ただしエラーはdeviceにdispatchするのではなくerrorとして捕捉する。 -
pipelineの パイプライン生成 (成功・失敗問わず)完了時に event が発生する。
-
タイムラインイベントを監視 event を this.
[[device]]で発生させ、以降の手順は デバイスタイムライン上で処理する。
デバイスタイムラインの手順:-
pipeline が 有効 または this が 失われている場合:
-
以下の手順を contentTimeline 上で実行:
コンテンツタイムラインの手順:-
promise を pipeline で解決する。
-
-
終了。
注: 失われたデバイスからはエラーは生成されません。 § 22 エラーとデバッグ参照。
-
-
pipeline が 無効 かつ error が 内部エラーの場合は、以下の手順を contentTimeline 上で実行して終了。
コンテンツタイムラインの手順:-
promise を
GPUPipelineErrorのreasonとして"internal"で reject する。
-
-
pipeline が 無効 であり、 error が バリデーションエラー の場合、 以下の手順を contentTimeline 上で実行して終了する。
コンテンツタイムラインの手順:-
promise を
GPUPipelineErrorのreasonとして"validation"で reject する。
-
-
引数:
-
GPURenderPipelineDescriptordescriptor -
GPUPipelineLayoutlayout -
GPUDevicedevice
デバイスタイムラインの手順:
-
以下すべての条件を満たせば
trueを返す:-
GPUVertexStateの検証(device, descriptor.
vertex, layout) が成功すること。 -
descriptor.
fragmentが指定されている場合:-
GPUFragmentStateの検証(device, descriptor.
fragment, layout) が成功すること。 -
sample_mask 組み込み値が descriptor.
fragmentの シェーダーステージ出力である場合:-
descriptor.
multisample.alphaToCoverageEnabledがfalseであること。
-
-
frag_depth 組み込み値が descriptor.
fragmentの シェーダーステージ出力である場合:-
descriptor.
depthStencilが指定されていること、かつ descriptor.depthStencil.formatがdepthアスペクトを持つこと。
-
-
-
GPUPrimitiveStateの検証(descriptor.
primitive, device) が成功すること。 -
descriptor.
depthStencilが指定されている場合:-
GPUDepthStencilStateの検証(descriptor.
depthStencil, descriptor.primitive.topology) が成功すること。
-
-
GPUMultisampleStateの検証(descriptor.
multisample) が成功すること。 -
descriptor.
multisample.alphaToCoverageEnabledが true の場合: -
少なくとも1つのアタッチメントが存在しなければならない。以下のいずれか:
-
descriptor.
depthStencil
-
ステージ間インターフェースの検証(device, descriptor) が
trueを返すこと。
-
引数:
-
GPUDevicedevice -
GPURenderPipelineDescriptordescriptor
戻り値: boolean
デバイスタイムラインの手順:
-
maxVertexShaderOutputVariables を device.limits.
maxInterStageShaderVariablesとする。 -
maxVertexShaderOutputLocation を device.limits.
maxInterStageShaderVariables- 1 とする。 -
descriptor.
primitive.topologyが"point-list"の場合:-
maxVertexShaderOutputVariables を 1 減算する。
-
-
clip_distances が descriptor.
vertexの出力で宣言されている場合:-
clipDistancesSize を clip_distances の配列サイズとする。
-
maxVertexShaderOutputVariables を ceil(clipDistancesSize / 4) 減算する。
-
maxVertexShaderOutputLocation を ceil(clipDistancesSize / 4) 減算する。
-
-
以下のいずれかの要件が満たされない場合は
falseを返す: -
descriptor.
fragmentが指定されている場合:-
maxFragmentShaderInputVariables を device.limits.
maxInterStageShaderVariablesとする。 -
front_facing,sample_index,sample_maskのいずれかの組み込み値が descriptor.fragmentの入力である場合:-
maxFragmentShaderInputVariables を 1 減算する。
-
-
以下のいずれかの要件が満たされない場合は
falseを返す: -
Assert 各ユーザー定義入力の locationが device.limits.
maxInterStageShaderVariables未満であること。 (上記ルールから導かれる。)
-
-
trueを返す。
GPURenderPipeline
の作成例:
const renderPipeline= gpuDevice. createRenderPipeline({ layout: pipelineLayout, vertex: { module: shaderModule, entryPoint: 'vertexMain' }, fragment: { module: shaderModule, entryPoint: 'fragmentMain' , targets: [{ format: 'bgra8unorm' , }], } });
10.3.2. プリミティブ状態
dictionary {GPUPrimitiveState GPUPrimitiveTopology topology = "triangle-list";GPUIndexFormat stripIndexFormat ;GPUFrontFace frontFace = "ccw";GPUCullMode cullMode = "none"; // Requires "depth-clip-control" feature.boolean unclippedDepth =false ; };
GPUPrimitiveState
には以下のメンバーがあり、GPURenderPipeline
が頂点入力からプリミティブを構築しラスタライズする方法を記述します:
topology, 型 GPUPrimitiveTopology、デフォルト値"triangle-list"-
頂点入力から構築するプリミティブの種類。
stripIndexFormat, 型 GPUIndexFormat-
ストリップトポロジー (
"line-strip"または"triangle-strip") のパイプラインに対して、インデックスバッファのフォーマットとプリミティブリスタート値 ("uint16"/0xFFFFまたは"uint32"/0xFFFFFFFF) を決定します。非ストリップトポロジーのパイプラインでは指定できません。注: 一部の実装では、プリミティブリスタート値の知識がパイプライン状態オブジェクトのコンパイルに必要です。
ストリップトポロジーのパイプラインをインデックス付きドローコール (
drawIndexed()またはdrawIndexedIndirect()) で使う場合、これを設定する必要があり、ドローコールで使うインデックスバッファのフォーマット (setIndexBuffer()で設定) と一致しなければなりません。詳細は § 23.2.3 プリミティブアセンブリ を参照してください。
frontFace, 型 GPUFrontFace、デフォルト値"ccw"-
どのポリゴンが表面とみなされるかを定義します。
cullMode, 型 GPUCullMode、デフォルト値"none"-
どのポリゴン方向をカリングするか(除去するか)を定義します。
unclippedDepth, 型 boolean、デフォルト値false-
true の場合、深度クリッピングが無効化されます。
"depth-clip-control"機能が有効化されている必要があります。
-
GPUPrimitiveStatedescriptor -
GPUDevicedevice
デバイスタイムラインの手順:
-
以下すべての条件を満たせば
trueを返す:-
descriptor.
topologyが"line-strip"または"triangle-strip"でない場合:-
descriptor.
stripIndexFormatが指定されていてはならない。
-
-
descriptor.
unclippedDepthがtrueの場合:-
"depth-clip-control"が device で有効化されていること。
-
-
enum {GPUPrimitiveTopology "point-list" ,"line-list" ,"line-strip" ,"triangle-list" ,"triangle-strip" , };
GPUPrimitiveTopology
は、GPURenderPipeline
で描画コールを行う際に使用されるプリミティブタイプを定義します。詳細は § 23.2.5 ラスタライズ を参照してください:
"point-list"-
各頂点が点プリミティブを定義します。
"line-list"-
連続する2頂点ごとに線プリミティブを定義します。
"line-strip"-
2頂点目以降の各頂点が前の頂点との間に線プリミティブを定義します。
"triangle-list"-
連続する3頂点ごとに三角形プリミティブを定義します。
"triangle-strip"-
3頂点目以降の各頂点が前の2頂点との間に三角形プリミティブを定義します。
enum {GPUFrontFace "ccw" ,"cw" , };
GPUFrontFace
は、GPURenderPipeline
によってどのポリゴンが表面とみなされるかを定義します。詳細は
§ 23.2.5.4 ポリゴンラスタライズ を参照してください:
enum {GPUCullMode "none" ,"front" ,"back" , };
GPUPrimitiveTopology
は、GPURenderPipeline
で描画コールを行う際にどのポリゴンがカリングされるかを定義します。詳細は § 23.2.5.4 ポリゴンラスタライズ を参照してください:
注: GPUFrontFace
および GPUCullMode
は、"point-list"、
"line-list"、
"line-strip"
トポロジーには影響しません。
10.3.3. マルチサンプル状態
dictionary {GPUMultisampleState GPUSize32 count = 1;GPUSampleMask mask = 0xFFFFFFFF;boolean alphaToCoverageEnabled =false ; };
GPUMultisampleState
には以下のメンバーがあり、GPURenderPipeline
がレンダーパスのマルチサンプル付きアタッチメントとどのように相互作用するかを記述します。
count, 型 GPUSize32、デフォルト値1-
ピクセルごとのサンプル数。この
GPURenderPipelineは、アタッチメントテクスチャ (colorAttachmentsおよびdepthStencilAttachment) のsampleCountが一致するものとだけ互換性があります。 mask, 型 GPUSampleMask、デフォルト値0xFFFFFFFF-
どのサンプルに書き込むかを決定するマスク。
alphaToCoverageEnabled, 型 boolean、デフォルト値false-
trueの場合、フラグメントのアルファチャンネルでサンプルカバレッジマスクを生成することを示します。
-
GPUMultisampleStatedescriptor
デバイスタイムラインの手順:
-
以下すべての条件を満たせば
trueを返す:-
descriptor.
countは 1 または 4 でなければならない。 -
descriptor.
alphaToCoverageEnabledがtrueの場合:-
descriptor.
count> 1 でなければならない。
-
-
10.3.4. フラグメント状態
dictionary :GPUFragmentState GPUProgrammableStage {required sequence <GPUColorTargetState ?>targets ; };
targets, 型sequence<GPUColorTargetState?>-
このパイプラインが書き込むカラ―ターゲットのフォーマットや動作を定義する
GPUColorTargetStateのリスト。
引数:
-
GPUDevicedevice -
GPUFragmentStatedescriptor -
GPUPipelineLayoutlayout
デバイスタイムラインの手順:
-
以下すべての要件が満たされていれば
trueを返す:-
GPUProgrammableStageの検証(
FRAGMENT, descriptor, layout, device) が成功すること。 -
descriptor.
targets.size が device.[[limits]].maxColorAttachments以下であること。 -
entryPoint を get the entry point(
FRAGMENT, descriptor) とする。 -
usesDualSourceBlending を
falseとする。 -
各 index について、descriptor.
targetsの非null値 colorStateに対して:-
colorState.
formatが § 26.1.1 プレーンカラーフォーマット に記載されていて、RENDER_ATTACHMENT機能を持つこと。 -
colorState.
writeMaskが 16 未満であること。 -
-
colorState.
blend.colorが有効なGPUBlendComponentであること。 -
colorState.
blend.alphaが有効なGPUBlendComponentであること。 -
colorState.
blend.color.srcFactorや colorState.blend.color.dstFactorや colorState.blend.alpha.srcFactorや colorState.blend.alpha.dstFactorが対応するブレンディングユニットの第2入力 ("src1"、"one-minus-src1"、"src1-alpha"、"one-minus-src1-alpha") を使う場合:-
usesDualSourceBlending を
trueにする。
-
-
各entryPointのシェーダーステージ出力値 output で location属性がindexと等しいものについて:
-
colorState.
formatの各成分に対応するoutputの成分があること (RGBAならvec4、RGBならvec3またはvec4、RGならvec2/vec3/vec4)。 -
GPUTextureSampleType( § 26.1 テクスチャフォーマット機能で定義)が:"float"や"unfilterable-float"-
output が浮動小数点スカラー型であること。
"sint"-
output が符号付き整数スカラー型であること。
"uint"-
output が符号なし整数スカラー型であること。
-
colorState.
blendが指定されていて、さらに colorState.blend.color.srcFactorや .dstFactorがソースアルファ ("src-alpha"、"one-minus-src-alpha"、"src-alpha-saturated"、"src1-alpha"や"one-minus-src1-alpha") を使う場合:-
output にアルファチャンネル (つまり vec4) が必要。
-
-
-
colorState.
writeMaskが 0 でない場合:-
entryPoint が シェーダーステージ出力 を持ち、blend_srcが省略または0で、 locationがindexと等しいこと。
-
-
-
usesDualSourceBlending が
trueの場合:-
すべてのシェーダーステージ出力は entryPoint内で同じstructに属し、 デュアルソースブレンディングを使う必要がある。
-
GPUFragmentStateのカラ―アタッチメントのバイト/サンプルの検証(device, descriptor.
targets) が成功すること。
-
引数:
-
GPUDevicedevice -
sequence<
GPUColorTargetState?> targets
デバイスタイムラインの手順:
-
formats を空のlist<
GPUTextureFormat?>とする。 -
targets の各 target について:
-
カラ―アタッチメントのバイト/サンプルの計算(formats) が device.
[[limits]].maxColorAttachmentBytesPerSample以下でなければならない。
注: フラグメントシェーダーは、パイプラインで使用される値よりも多くの値を出力する場合があります。その場合、値は無視されます。
GPUBlendComponent
component は論理device
deviceで下記要件を満たす場合、有効なGPUBlendComponentです:
10.3.5. カラ―ターゲット状態
dictionary {GPUColorTargetState required GPUTextureFormat format ;GPUBlendState blend ;GPUColorWriteFlags writeMask = 0xF; // GPUColorWrite.ALL };
format, 型 GPUTextureFormat-
このカラ―ターゲットの
GPUTextureFormat。 パイプラインは、対応するカラ―アタッチメントにこのフォーマットのGPUTextureViewを使うGPURenderPassEncoderとだけ互換性があります。 blend, 型 GPUBlendState-
このカラ―ターゲットのブレンディングの挙動。未定義の場合、ブレンディングは無効化されます。
writeMask, 型 GPUColorWriteFlags、デフォルト値0xF-
このカラ―ターゲットへの描画時に、どのチャンネルに書き込むかを制御するビットマスク。
dictionary {GPUBlendState required GPUBlendComponent color ;required GPUBlendComponent alpha ; };
color, 型 GPUBlendComponent-
対応するレンダーターゲットのカラーチャンネルのブレンディング挙動を定義します。
alpha, 型 GPUBlendComponent-
対応するレンダーターゲットのアルファチャンネルのブレンディング挙動を定義します。
typedef [EnforceRange ]unsigned long ; [GPUColorWriteFlags Exposed =(Window ,Worker ),SecureContext ]namespace {GPUColorWrite const GPUFlagsConstant = 0x1;RED const GPUFlagsConstant = 0x2;GREEN const GPUFlagsConstant = 0x4;BLUE const GPUFlagsConstant = 0x8;ALPHA const GPUFlagsConstant = 0xF; };ALL
10.3.5.1. ブレンド状態
dictionary {GPUBlendComponent GPUBlendOperation operation = "add";GPUBlendFactor srcFactor = "one";GPUBlendFactor dstFactor = "zero"; };
GPUBlendComponent
には以下のメンバーがあり、フラグメントのカラーおよびアルファ成分のブレンド方法を記述します:
operation, 型 GPUBlendOperation、デフォルト値"add"-
ターゲットアタッチメント成分に書き込まれる値の計算に使われる
GPUBlendOperationを定義します。 srcFactor, 型 GPUBlendFactor、デフォルト値"one"-
フラグメントシェーダーからの値に対して行う
GPUBlendFactorの操作を定義します。 dstFactor, 型 GPUBlendFactor、デフォルト値"zero"-
ターゲットアタッチメントからの値に対して行う
GPUBlendFactorの操作を定義します。
以下の表は、あるフラグメント位置でのカラー成分を記述するための記法を示します:
RGBAsrc
| カラ―アタッチメントに対してフラグメントシェーダーが出力したカラー。 シェーダーがアルファチャンネルを返さない場合、src-alpha ブレンドファクターは使用できません。 |
RGBAsrc1
| カラ―アタッチメントに対して、"@blend_src" 属性
が 1 のフラグメントシェーダーのカラー出力。
シェーダーがアルファチャンネルを返さない場合、src1-alpha ブレンドファクターは使用できません。
|
RGBAdst
| カラ―アタッチメントに現在入っているカラー。
グリーン/ブルー/アルファチャンネルがない場合は、デフォルトで 0, 0, 1 となります。
|
RGBAconst
| 現在の [[blendConstant]]。
|
RGBAsrcFactor
| srcFactor
で定義されたソースブレンドファクター成分。
|
RGBAdstFactor
| dstFactor
で定義されたデスティネーションブレンドファクター成分。
|
enum {GPUBlendFactor "zero" ,"one" ,"src" ,"one-minus-src" ,"src-alpha" ,"one-minus-src-alpha" ,"dst" ,"one-minus-dst" ,"dst-alpha" ,"one-minus-dst-alpha" ,"src-alpha-saturated" ,"constant" ,"one-minus-constant" ,"src1" ,"one-minus-src1" ,"src1-alpha" ,"one-minus-src1-alpha" , };
GPUBlendFactor
はソースまたはデスティネーションのブレンドファクターがどのように計算されるかを定義します:
| GPUBlendFactor | ブレンドファクター RGBA 成分 | 機能 |
|---|---|---|
"zero"
| (0, 0, 0, 0)
| |
"one"
| (1, 1, 1, 1)
| |
"src"
| (Rsrc, Gsrc, Bsrc, Asrc)
| |
"one-minus-src"
| (1 - Rsrc, 1 - Gsrc, 1 - Bsrc, 1 - Asrc)
| |
"src-alpha"
| (Asrc, Asrc, Asrc, Asrc)
| |
"one-minus-src-alpha"
| (1 - Asrc, 1 - Asrc, 1 - Asrc, 1 - Asrc)
| |
"dst"
| (Rdst, Gdst, Bdst, Adst)
| |
"one-minus-dst"
| (1 - Rdst, 1 - Gdst, 1 - Bdst, 1 - Adst)
| |
"dst-alpha"
| (Adst, Adst, Adst, Adst)
| |
"one-minus-dst-alpha"
| (1 - Adst, 1 - Adst, 1 - Adst, 1 - Adst)
| |
"src-alpha-saturated"
| (min(Asrc, 1 - Adst), min(Asrc, 1 - Adst), min(Asrc, 1 - Adst), 1)
| |
"constant"
| (Rconst, Gconst, Bconst, Aconst)
| |
"one-minus-constant"
| (1 - Rconst, 1 - Gconst, 1 - Bconst, 1 - Aconst)
| |
"src1"
| (Rsrc1, Gsrc1, Bsrc1, Asrc1)
| dual-source-blending
|
"one-minus-src1"
| (1 - Rsrc1, 1 - Gsrc1, 1 - Bsrc1, 1 - Asrc1)
| |
"src1-alpha"
| (Asrc1, Asrc1, Asrc1, Asrc1)
| |
"one-minus-src1-alpha"
| (1 - Asrc1, 1 - Asrc1, 1 - Asrc1, 1 - Asrc1)
|
enum {GPUBlendOperation "add" ,"subtract" ,"reverse-subtract" ,"min" ,"max" , };
GPUBlendOperation
はソースとデスティネーションのブレンドファクターを組み合わせるアルゴリズムを定義します:
| GPUBlendOperation | RGBA成分 |
|---|---|
"add"
| RGBAsrc × RGBAsrcFactor + RGBAdst × RGBAdstFactor
|
"subtract"
| RGBAsrc × RGBAsrcFactor - RGBAdst × RGBAdstFactor
|
"reverse-subtract"
| RGBAdst × RGBAdstFactor - RGBAsrc × RGBAsrcFactor
|
"min"
| min(RGBAsrc, RGBAdst)
|
"max"
| max(RGBAsrc, RGBAdst)
|
10.3.6. デプス・ステンシル状態
dictionary {GPUDepthStencilState required GPUTextureFormat format ;boolean depthWriteEnabled ;GPUCompareFunction depthCompare ;GPUStencilFaceState stencilFront = {};GPUStencilFaceState stencilBack = {};GPUStencilValue stencilReadMask = 0xFFFFFFFF;GPUStencilValue stencilWriteMask = 0xFFFFFFFF;GPUDepthBias depthBias = 0;float depthBiasSlopeScale = 0;float depthBiasClamp = 0; };
GPUDepthStencilState
には以下のメンバーがあり、GPURenderPipeline
がレンダーパスのdepthStencilAttachment
にどのような影響を与えるかを記述します:
format, 型 GPUTextureFormat-
この
GPURenderPipelineが互換性を持つdepthStencilAttachmentのformat。 depthWriteEnabled, 型 boolean-
この
GPURenderPipelineがdepthStencilAttachmentの深度値を書き換えることができるかを示します。 depthCompare, 型 GPUCompareFunction-
フラグメントの深度値を
depthStencilAttachmentの深度値と比較するための演算方法。 stencilFront, 型 GPUStencilFaceState、デフォルト値{}-
表面プリミティブに対してステンシル比較・操作をどのように行うかを定義します。
stencilBack, 型 GPUStencilFaceState、デフォルト値{}-
裏面プリミティブに対してステンシル比較・操作をどのように行うかを定義します。
stencilReadMask, 型 GPUStencilValue、デフォルト値0xFFFFFFFF-
ステンシル比較テストを行う際に、どの
depthStencilAttachmentのステンシル値ビットを読み取るかを制御するビットマスク。 stencilWriteMask, 型 GPUStencilValue、デフォルト値0xFFFFFFFF-
ステンシル操作を行う際に、どの
depthStencilAttachmentのステンシル値ビットに書き込むかを制御するビットマスク。 depthBias, 型 GPUDepthBias、デフォルト値0-
各三角形フラグメントに加算される定数深度バイアス。詳細はバイアス付きフラグメント深度参照。
depthBiasSlopeScale, 型 float、デフォルト値0-
三角形フラグメントの傾きに応じてスケールされる深度バイアス。詳細はバイアス付きフラグメント深度参照。
depthBiasClamp, 型 float、デフォルト値0-
三角形フラグメントの最大深度バイアス。詳細はバイアス付きフラグメント深度参照。
注: depthBias、
depthBiasSlopeScale、
および
depthBiasClamp
は"point-list"、
"line-list"、
"line-strip"
プリミティブには効果がなく、0でなければなりません。
depthStencilAttachment
attachmentに対して
GPUDepthStencilState
stateを使って描画する際、以下のキュータイムラインの手順で計算されます:
-
r を format における0より大きい最小の正の表現可能値(32ビットfloatに変換)とする。
-
maxDepthSlope をフラグメントの深度値の水平・垂直方向の最大傾きとする。
-
format がunormフォーマットの場合:
-
bias を
(float)state.とする。depthBias* r + state.depthBiasSlopeScale* maxDepthSlope
-
-
それ以外でformatがfloatフォーマットの場合:
-
bias を
(float)state.とする。depthBias* 2^(exp(max depth in primitive) - r) + state.depthBiasSlopeScale* maxDepthSlope
-
-
state.
depthBiasClamp>0の場合:-
bias を
min(state.とする。depthBiasClamp, bias)
-
-
それ以外でstate.
depthBiasClamp<0の場合:-
bias を
max(state.とする。depthBiasClamp, bias)
-
-
state.
depthBias≠0または state.depthBiasSlopeScale≠0の場合:-
フラグメントの深度値に
fragment depth value + biasを設定する。
-
引数:
-
GPUDepthStencilStatedescriptor -
GPUPrimitiveTopologytopology
デバイスタイムラインの手順:
-
以下のすべての条件を満たした場合に限り、
trueを返す:-
descriptor.
formatがdepth-or-stencil フォーマットである。 -
descriptor.
depthWriteEnabledがtrueまたは descriptor.depthCompareが指定されていて、かつ"always"でない場合:-
descriptor.
formatはdepth成分を持たなければならない。
-
-
descriptor.
stencilFrontまたは descriptor.stencilBackがデフォルト値でない場合:-
descriptor.
formatはstencil成分を持たなければならない。
-
-
descriptor.
formatがdepth成分を持つ場合:-
descriptor.
depthWriteEnabledが指定されていなければならない。 -
以下の場合、descriptor.
depthCompareが指定されていなければならない:-
descriptor.
depthWriteEnabledがtrueである場合 -
descriptor.
stencilFront.depthFailOpが"keep"でない場合 -
descriptor.
stencilBack.depthFailOpが"keep"でない場合
-
-
-
topology が
"point-list"、"line-list"、"line-strip"の場合:-
descriptor.
depthBiasは 0 でなければならない。 -
descriptor.
depthBiasSlopeScaleは 0 でなければならない。 -
descriptor.
depthBiasClampは 0 でなければならない。
-
-
dictionary {GPUStencilFaceState GPUCompareFunction compare = "always";GPUStencilOperation failOp = "keep";GPUStencilOperation depthFailOp = "keep";GPUStencilOperation passOp = "keep"; };
GPUStencilFaceState
には以下のメンバーがあり、ステンシル比較と操作の方法を記述します:
compare, 型 GPUCompareFunction、デフォルト値"always"-
フラグメントの
depthStencilAttachmentのステンシル値に対して[[stencilReference]]の値をテストする際に使用されるGPUCompareFunction。 failOp, 型 GPUStencilOperation、デフォルト値"keep"-
compareで記述されるフラグメントステンシル比較テストに失敗した場合に実行されるGPUStencilOperation。 depthFailOp, 型 GPUStencilOperation、デフォルト値"keep"-
depthCompareで記述されるフラグメント深度比較に失敗した場合に実行されるGPUStencilOperation。 passOp, 型 GPUStencilOperation、デフォルト値"keep"-
compareで記述されるフラグメントステンシル比較テストに成功した場合に実行されるGPUStencilOperation。
enum {GPUStencilOperation "keep" ,"zero" ,"replace" ,"invert" ,"increment-clamp" ,"decrement-clamp" ,"increment-wrap" ,"decrement-wrap" , };
GPUStencilOperation
では以下の操作を定義します:
"keep"-
現在のステンシル値を保持します。
"zero"-
ステンシル値を
0に設定します。 "replace"-
ステンシル値を
[[stencilReference]]に設定します。 "invert"-
現在のステンシル値をビット反転します。
"increment-clamp"-
現在のステンシル値をインクリメントし、
depthStencilAttachmentの ステンシルアスペクトの最大表現値までクランプします。 "decrement-clamp"-
現在のステンシル値をデクリメントし、
0までクランプします。 "increment-wrap"-
現在のステンシル値をインクリメントし、値が最大表現値を超えた場合はゼロにラップします(
depthStencilAttachmentの ステンシルアスペクト)。 "decrement-wrap"-
現在のステンシル値をデクリメントし、値が
0未満になった場合はdepthStencilAttachmentの ステンシルアスペクトの最大表現値にラップします。
10.3.7. バーテックス状態
enum {GPUIndexFormat "uint16" ,"uint32" , };
インデックスフォーマットは、バッファ内のインデックス値のデータ型を決定し、ストリッププリミティブトポロジー
("line-strip"
または
"triangle-strip")
で使用される場合は、プリミティブリスタート値も指定します。
プリミティブリスタート値は、
どのインデックス値が新しいプリミティブの開始を示すか(以前のインデックス頂点でストリップを継続するのではなく)を示します。
GPUPrimitiveState
でストリッププリミティブトポロジーを指定する場合、インデックス付き描画に使う場合は
stripIndexFormat
を必ず指定し、パイプライン生成時に使用される
プリミティブリスタート値が分かるようにします。
GPUPrimitiveState
でリストトポロジーを指定する場合は、
インデックス付き描画時にsetIndexBuffer()
で渡したインデックスフォーマットを使います。
| インデックスフォーマット | バイトサイズ | プリミティブリスタート値 |
|---|---|---|
"uint16"
| 2 | 0xFFFF |
"uint32"
| 4 | 0xFFFFFFFF |
10.3.7.1. バーテックスフォーマット
GPUVertexFormat
はバーテックス属性のデータがバーテックスバッファからどのように解釈・シェーダーへ公開されるかを示します。
フォーマット名は成分の順序、各成分のビット数、および成分のバーテックスデータ型を指定します。
各バーテックスデータ型は、 ビット数に関係なく、同じ基本型のWGSLスカラー型にマッピングできます:
| バーテックスフォーマット接頭辞 | バーテックスデータ型 | 対応するWGSL型 |
|---|---|---|
uint
| 符号なし整数 | u32
|
sint
| 符号付き整数 | i32
|
unorm
| 符号なし正規化 | f16, f32
|
snorm
| 符号付き正規化 | |
float
| 浮動小数点 |
複数成分フォーマットでは "x" の後の数字が成分数を示します。バーテックスフォーマットとシェーダー型の成分数が一致しない場合は、成分が切り捨てられるかデフォルト値で埋められます。
"unorm8x2"
のバーテックス属性と、バイト値 [0x7F, 0xFF]
を持つ場合、シェーダーでは以下の型でアクセスできます:
| シェーダー型 | シェーダー値 |
|---|---|
f16
| 0.5h
|
f32
| 0.5f
|
vec2<f16>
| vec2(0.5h, 1.0h)
|
vec2<f32>
| vec2(0.5f, 1.0f)
|
vec3<f16>
| vec2(0.5h, 1.0h, 0.0h)
|
vec3<f32>
| vec2(0.5f, 1.0f, 0.0f)
|
vec4<f16>
| vec2(0.5h, 1.0h, 0.0h, 1.0h)
|
vec4<f32>
| vec2(0.5f, 1.0f, 0.0f, 1.0f)
|
バーテックスフォーマットがシェーダーでどのように公開されるかは § 23.2.2 バーテックス処理 を参照してください。
enum {GPUVertexFormat "uint8" ,"uint8x2" ,"uint8x4" ,"sint8" ,"sint8x2" ,"sint8x4" ,"unorm8" ,"unorm8x2" ,"unorm8x4" ,"snorm8" ,"snorm8x2" ,"snorm8x4" ,"uint16" ,"uint16x2" ,"uint16x4" ,"sint16" ,"sint16x2" ,"sint16x4" ,"unorm16" ,"unorm16x2" ,"unorm16x4" ,"snorm16" ,"snorm16x2" ,"snorm16x4" ,"float16" ,"float16x2" ,"float16x4" ,"float32" ,"float32x2" ,"float32x3" ,"float32x4" ,"uint32" ,"uint32x2" ,"uint32x3" ,"uint32x4" ,"sint32" ,"sint32x2" ,"sint32x3" ,"sint32x4" ,"unorm10-10-10-2" ,"unorm8x4-bgra" , };
| バーテックスフォーマット | データ型 | 成分数 | バイトサイズ | WGSL型例 |
|---|---|---|---|---|
"uint8"
| 符号なし整数 | 1 | 1 | u32
|
"uint8x2"
| 符号なし整数 | 2 | 2 | vec2<u32>
|
"uint8x4"
| 符号なし整数 | 4 | 4 | vec4<u32>
|
"sint8"
| 符号付き整数 | 1 | 1 | i32
|
"sint8x2"
| 符号付き整数 | 2 | 2 | vec2<i32>
|
"sint8x4"
| 符号付き整数 | 4 | 4 | vec4<i32>
|
"unorm8"
| 符号なし正規化 | 1 | 1 | f32
|
"unorm8x2"
| 符号なし正規化 | 2 | 2 | vec2<f32>
|
"unorm8x4"
| 符号なし正規化 | 4 | 4 | vec4<f32>
|
"snorm8"
| 符号付き正規化 | 1 | 1 | f32
|
"snorm8x2"
| 符号付き正規化 | 2 | 2 | vec2<f32>
|
"snorm8x4"
| 符号付き正規化 | 4 | 4 | vec4<f32>
|
"uint16"
| 符号なし整数 | 1 | 2 | u32
|
"uint16x2"
| 符号なし整数 | 2 | 4 | vec2<u32>
|
"uint16x4"
| 符号なし整数 | 4 | 8 | vec4<u32>
|
"sint16"
| 符号付き整数 | 1 | 2 | i32
|
"sint16x2"
| 符号付き整数 | 2 | 4 | vec2<i32>
|
"sint16x4"
| 符号付き整数 | 4 | 8 | vec4<i32>
|
"unorm16"
| 符号なし正規化 | 1 | 2 | f32
|
"unorm16x2"
| 符号なし正規化 | 2 | 4 | vec2<f32>
|
"unorm16x4"
| 符号なし正規化 | 4 | 8 | vec4<f32>
|
"snorm16"
| 符号付き正規化 | 1 | 2 | f32
|
"snorm16x2"
| 符号付き正規化 | 2 | 4 | vec2<f32>
|
"snorm16x4"
| 符号付き正規化 | 4 | 8 | vec4<f32>
|
"float16"
| 浮動小数点 | 1 | 2 | f32
|
"float16x2"
| 浮動小数点 | 2 | 4 | vec2<f16>
|
"float16x4"
| 浮動小数点 | 4 | 8 | vec4<f16>
|
"float32"
| 浮動小数点 | 1 | 4 | f32
|
"float32x2"
| 浮動小数点 | 2 | 8 | vec2<f32>
|
"float32x3"
| 浮動小数点 | 3 | 12 | vec3<f32>
|
"float32x4"
| 浮動小数点 | 4 | 16 | vec4<f32>
|
"uint32"
| 符号なし整数 | 1 | 4 | u32
|
"uint32x2"
| 符号なし整数 | 2 | 8 | vec2<u32>
|
"uint32x3"
| 符号なし整数 | 3 | 12 | vec3<u32>
|
"uint32x4"
| 符号なし整数 | 4 | 16 | vec4<u32>
|
"sint32"
| 符号付き整数 | 1 | 4 | i32
|
"sint32x2"
| 符号付き整数 | 2 | 8 | vec2<i32>
|
"sint32x3"
| 符号付き整数 | 3 | 12 | vec3<i32>
|
"sint32x4"
| 符号付き整数 | 4 | 16 | vec4<i32>
|
"unorm10-10-10-2"
| 符号なし正規化 | 4 | 4 | vec4<f32>
|
"unorm8x4-bgra"
| 符号なし正規化 | 4 | 4 | vec4<f32>
|
enum {GPUVertexStepMode "vertex" ,"instance" , };
ステップモードは、現在のバーテックスまたはインスタンスインデックスに基づいて、バーテックスバッファデータのアドレス計算方法を設定します:
"vertex"-
各バーテックスごとに
arrayStrideでアドレスが進み、 インスタンスごとにリセットされます。 "instance"-
各インスタンスごとに
arrayStrideでアドレスが進みます。
dictionary :GPUVertexState GPUProgrammableStage {sequence <GPUVertexBufferLayout ?>buffers = []; };
buffers, 型sequence<GPUVertexBufferLayout?>、デフォルト値[]-
このパイプラインで使用するバーテックスバッファのバーテックス属性データのレイアウトを定義する
GPUVertexBufferLayoutのリスト。
バーテックスバッファは概念的には
バッファメモリへの構造体の配列としてのビューです。
arrayStride
は、その配列の要素間のバイト単位のストライドです。
バーテックスバッファの各要素は、メモリレイアウトが
attributes
で定義された構造体のようなもので、
それぞれが構造体のメンバーとなります。
各GPUVertexAttribute
は
format
と
offset
(バイト単位) を構造体内の位置として記述します。
各属性はバーテックスシェーダーで個別の入力として表れ、それぞれ数値のlocationにバインドされます。
このlocationはshaderLocation
で指定され、GPUVertexState
内で一意でなければなりません。
dictionary {GPUVertexBufferLayout required GPUSize64 arrayStride ;GPUVertexStepMode stepMode = "vertex";required sequence <GPUVertexAttribute >attributes ; };
arrayStride, 型 GPUSize64-
この配列の要素間のバイト単位のストライド。
stepMode, 型 GPUVertexStepMode、デフォルト値"vertex"-
この配列の各要素が頂点ごとのデータかインスタンスごとのデータか。
attributes, 型 sequence<GPUVertexAttribute>-
各要素内のバーテックス属性のレイアウトを定義する配列。
dictionary {GPUVertexAttribute required GPUVertexFormat format ;required GPUSize64 offset ;required GPUIndex32 shaderLocation ; };
format, 型 GPUVertexFormat-
この属性の
GPUVertexFormat。 offset, 型 GPUSize64-
その属性のデータが要素の先頭から何バイト目か。
shaderLocation, 型 GPUIndex32-
この属性に関連付けられる数値のlocationで、
vertex.moduleで宣言する "@location" 属性 に対応します。
引数:
-
GPUDevicedevice -
GPUVertexBufferLayoutdescriptor
デバイスタイムラインの手順:
-
以下のすべての条件を満たした場合に限り、
trueを返す:-
descriptor.
arrayStride≤ device.[[device]].[[limits]].maxVertexBufferArrayStride。 -
descriptor.
arrayStrideが4の倍数である。 -
リストdescriptor.
attributesの各属性attribについて:-
descriptor.
arrayStrideがゼロの場合:-
attrib.
offset+ byteSize(attrib.format) ≤ device.[[device]].[[limits]].maxVertexBufferArrayStride。
それ以外の場合:
-
attrib.
offset+ byteSize(attrib.format) ≤ descriptor.arrayStride。
-
-
attrib.
shaderLocationが device.[[device]].[[limits]].maxVertexAttributes未満である。
-
-
引数:
-
GPUDevicedevice -
GPUVertexStatedescriptor -
GPUPipelineLayoutlayout
デバイスタイムラインの手順:
-
entryPoint を get the entry point(
VERTEX, descriptor) とする。 -
Assert entryPoint が
nullでないこと。 -
以下の手順のすべての要件を満たさなければならない。
-
GPUProgrammableStageの検証(
VERTEX, descriptor, layout, device) が成功すること。 -
descriptor.
buffers.size が device.[[device]].[[limits]].maxVertexBuffers以下であること。 -
リスト descriptor.
buffersの各 vertexBuffer レイアウト記述子が GPUVertexBufferLayoutの検証(device, vertexBuffer) をパスすること。 -
すべての vertexBuffer.
attributes.size の合計が descriptor.buffers全体で device.[[device]].[[limits]].maxVertexAttributes以下であること。 -
エントリポイント entryPoint で静的に使用される各バーテックス属性宣言 (location location、型 T) について、 descriptor.
buffers[i]? .attributes[j] .shaderLocation== location となる組がちょうど1つ存在しなければならない。その
GPUVertexAttributeを attrib とする。 -
T が attrib.
formatの バーテックスデータ型と互換性があること:- "unorm", "snorm", "float"
-
T は
f32またはvecN<f32>でなければならない。 - "uint"
-
T は
u32またはvecN<u32>でなければならない。 - "sint"
-
T は
i32またはvecN<i32>でなければならない。
-
11. コピー
11.1. バッファコピー
バッファコピー操作は生のバイト単位で行われます。
WebGPUは「バッファ化」された GPUCommandEncoder
コマンドを提供します:
および「即時」 GPUQueue
操作:
-
writeBuffer()(ArrayBufferからGPUBufferへの書き込み)
11.2. テクセルコピー
テクセルコピー操作はバイト単位ではなくテクスチャ(画像)データを対象とします。
WebGPUは「バッファ化」された GPUCommandEncoder
コマンドを提供します:
および「即時」 GPUQueue
操作:
-
writeTexture()(ArrayBufferからGPUTextureへの書き込み) -
copyExternalImageToTexture()(Webプラットフォームの画像ソースからテクスチャへのコピー)
テクセルコピー中、テクセルは同等のテクセル表現でコピーされます。 テクセルコピーは、ソースの有効な通常の数値がデスティネーションでも同じ数値になることのみ保証し、以下の値のビット表現は保持されない場合があります:
-
snorm値は -1.0 を -127 または -128 のどちらでも表現可能です。
-
ゼロ値の符号は保持されない場合があります。
-
非正規化浮動小数点値は -0.0 または +0.0 に置き換えられる場合があります。
-
NaNやInfinityは無効値であり、不定値に置き換えられる場合があります。
注: コピーはWGSLシェーダーで実施される場合があり、その場合 WGSL浮動小数点の挙動が観測されることがあります。
以下の定義がこれらのメソッドで使われます:
11.2.1. GPUTexelCopyBufferLayout
"GPUTexelCopyBufferLayout"
はバイト配列(GPUBuffer
または AllowSharedBufferSource)の中のテクセルのレイアウトを
"テクセルコピー"操作で記述します。
dictionary GPUTexelCopyBufferLayout {GPUSize64 offset = 0;GPUSize32 bytesPerRow ;GPUSize32 rowsPerImage ; };
テクセル画像は1つ以上のテクセルブロックの行から構成され、ここではテクセルブロック行と呼びます。
各テクセルブロック行は同じ数のテクセルブロックを含み、
1つのテクセル画像内のすべてのテクセルブロックは同じGPUTextureFormatです。
GPUTexelCopyBufferLayout
は、線形メモリ内のテクセル画像のレイアウトです。
テクスチャとGPUBuffer間でデータをコピーする場合や、
GPUQueueからテクスチャに書き込む場合に使用されます。
バイト配列とテクスチャ間のコピー操作は常にテクセルブロック単位で行われます。 テクセルブロックの一部のみを更新することはできません。
テクセルブロックは各テクセルブロック行内で密に配置されており、 メモリレイアウト上、各テクセルブロックは直前のテクセルブロックの直後に続きます(パディングなし)。 これは特定アスペクトのコピー(depth-or-stencil formatテクスチャへの/からのコピー)にも当てはまります。 ステンシル値はバイト配列として密に配置され、 深度値は対応する型("depth16unorm"や"depth32float")の配列として密に配置されます。
offset, 型 GPUSize64、デフォルト値0-
テクセルデータソース(例:
GPUTexelCopyBufferInfo.buffer)の先頭からテクセルデータの開始位置までのバイトオフセット。 bytesPerRow, 型 GPUSize32-
各テクセルブロック行の先頭から次のテクセルブロック行までのバイト単位のストライド。
複数のテクセルブロック行(コピーの高さや深さが1ブロックを超える場合)では必須。
rowsPerImage, 型 GPUSize32-
1つのテクスチャのテクセル画像あたりのテクセルブロック行の数。
rowsPerImage×bytesPerRowは各テクセル画像の先頭から次のテクセル画像までのバイト単位のストライドです。複数のテクセル画像(コピー深度が1を超える場合)では必須。
11.2.2. GPUTexelCopyBufferInfo
"GPUTexelCopyBufferInfo"
は「info」(GPUBufferと
GPUTexelCopyBufferLayout)を
"テクセルコピー"操作のバッファのソースまたはデスティネーションとして記述します。
copySizeと合わせて、GPUBuffer内のテクセル領域のフットプリントを記述します。
dictionary GPUTexelCopyBufferInfo :GPUTexelCopyBufferLayout {required GPUBuffer buffer ; };
buffer, 型 GPUBuffer-
コピーされるテクセルデータを保持する、またはコピー後のテクセルデータが格納されるバッファ(メソッドにより異なる)。
引数:
-
GPUTexelCopyBufferInfoimageCopyBuffer
戻り値: boolean
デバイスタイムラインの手順:
-
以下すべての条件を満たした場合に限り
trueを返す:-
imageCopyBuffer.
bytesPerRowが256の倍数であること。
11.2.3. GPUTexelCopyTextureInfo
"GPUTexelCopyTextureInfo"
は「info」(GPUTextureなど)
を "テクセルコピー"操作のテクスチャのソースまたはデスティネーションとして記述します。
copySizeと合わせて、テクスチャのサブ領域
(同じミップマップレベル上の1つ以上の連続したテクスチャサブリソース)を記述します。
dictionary GPUTexelCopyTextureInfo {required GPUTexture texture ;GPUIntegerCoordinate mipLevel = 0;GPUOrigin3D origin = {};GPUTextureAspect aspect = "all"; };
texture, 型 GPUTexture-
コピー元またはコピー先のテクスチャ。
mipLevel, 型 GPUIntegerCoordinate、デフォルト値0-
コピー元またはコピー先の
textureのミップマップレベル。 origin, 型 GPUOrigin3D、デフォルト値{}-
コピーの原点(コピー元またはコピー先のテクスチャサブ領域の最小コーナー)。
copySizeと合わせてコピーサブ領域全体を定義します。 aspect, 型 GPUTextureAspect、デフォルト値"all"-
コピー元またはコピー先の
textureのどのアスペクトをコピーするかを定義します。
GPUTexelCopyTextureInfo
copyTextureのdepth sliceまたはarray layerindexに対して、以下の手順で決定されます:
GPUTexelCopyBufferLayout
bufferLayoutで記述されるデータの、GPUTexture
textureのdepth sliceまたはarray layerzのテクセルブロック
x, yに対して以下の手順で決定されます:
-
blockBytes を texture.
formatのテクセルブロックコピーのフットプリントとする。 -
imageOffset を (z × bufferLayout.
rowsPerImage× bufferLayout.bytesPerRow) + bufferLayout.offsetとする。 -
rowOffset を (y × bufferLayout.
bytesPerRow) + imageOffsetとする。 -
blockOffset を (x × blockBytes) + rowOffsetとする。
-
blockOffsetを返す。
引数:
-
GPUTexelCopyTextureInfotexelCopyTextureInfo -
GPUExtent3DcopySize
戻り値: boolean
デバイスタイムラインの手順:
-
blockWidth を texelCopyTextureInfo.
texture.formatのテクセルブロック幅とする。 -
blockHeight を texelCopyTextureInfo.
texture.formatのテクセルブロック高さとする。 -
以下すべての条件を満たした場合に限り
trueを返す:-
テクスチャコピー範囲の検証(texelCopyTextureInfo, copySize) が
trueを返すこと。 -
texelCopyTextureInfo.
textureが有効なGPUTextureであること。 -
texelCopyTextureInfo.
mipLevelが texelCopyTextureInfo.texture.mipLevelCount未満であること。 -
GPUTexelCopyTextureInfo物理サブリソースサイズがtexelCopyTextureInfoに対して copySizeと等しい場合、以下のいずれかの条件が真でなければならない:
-
texelCopyTextureInfo.
texture.sampleCount> 1 の場合。
-
引数:
-
GPUTexelCopyTextureInfotexelCopyTextureInfo -
GPUTexelCopyBufferLayoutbufferLayout -
GPUSize64OutdataLength -
GPUExtent3DcopySize -
GPUTextureUsagetextureUsage -
booleanaligned
戻り値: boolean
デバイスタイムラインの手順:
-
texture を texelCopyTextureInfo.
textureとする -
aspectSpecificFormat = texture.
formatとする -
offsetAlignment = texture.
formatのテクセルブロックコピーのフットプリントとする。 -
以下すべての条件を満たした場合に限り
trueを返す:-
GPUTexelCopyTextureInfoの検証(texelCopyTextureInfo, copySize) が
trueを返すこと。 -
texture.
sampleCountが1であること。 -
texture.
usageにtextureUsageが含まれていること。 -
texture.
formatがdepth-or-stencil formatの場合:-
texelCopyTextureInfo.
aspectがtexture.formatの単一アスペクトを参照していること。 -
textureUsageが以下の場合:
COPY_SRC-
そのアスペクトがテクセルコピーの有効なソースである必要があります(§ 26.1.2 デプスステンシルフォーマット参照)。
COPY_DST-
そのアスペクトがテクセルコピーの有効なデスティネーションである必要があります(§ 26.1.2 デプスステンシルフォーマット参照)。
-
aspectSpecificFormatをアスペクト固有フォーマットに設定(§ 26.1.2 デプスステンシルフォーマット参照)。
-
offsetAlignmentを4に設定。
-
-
alignedが
trueの場合:-
bufferLayout.
offsetがoffsetAlignmentの倍数であること。
-
-
リニアテクスチャデータの検証(bufferLayout, dataLength, aspectSpecificFormat, copySize)が成功すること。
-
11.2.4.
GPUCopyExternalImageDestInfo
WebGPUのテクスチャは生の数値データを保持し、色を説明するセマンティックなメタデータはタグ付けされません。
しかし、copyExternalImageToTexture()
は色を記述するソースからコピーします。
"GPUCopyExternalImageDestInfo"
は「destination」(コピー先)の「info」を
"copyExternalImageToTexture()"操作で説明します。
これはGPUTexelCopyTextureInfo
であり、さらに
色空間/エンコーディングおよびアルファ事前乗算のメタデータがタグ付けされることで、コピー時にセマンティックな色情報を保持できます。
このメタデータはコピー操作のセマンティクスのみに影響し、コピー先テクスチャオブジェクトの状態やセマンティクスには影響しません。
dictionary GPUCopyExternalImageDestInfo :GPUTexelCopyTextureInfo {PredefinedColorSpace colorSpace = "srgb";boolean premultipliedAlpha =false ; };
colorSpace, 型 PredefinedColorSpace、デフォルト値"srgb"-
コピー先のテクスチャへデータをエンコードする際の色空間とエンコーディングを記述します。
この変換により、書き込まれる値が[0, 1]範囲外になる場合があります(テクスチャフォーマットが表現できる場合)。 そうでない場合は、結果がテクスチャフォーマットの範囲にクランプされます。
注:
colorSpaceがソース画像と一致する場合、 変換は不要な場合があります。§ 3.10.2 色空間変換省略参照。 premultipliedAlpha, 型 boolean、デフォルト値false-
テクスチャへ書き込むデータのRGBチャンネルがアルファチャンネルで事前乗算されるか否かを記述します。
このオプションが
trueで、sourceも事前乗算済みの場合、ソースRGB値は対応するアルファ値を超えていても保持されなければなりません。注:
premultipliedAlphaがソース画像と一致する場合、 変換は不要な場合があります。§ 3.10.2 色空間変換省略参照。
11.2.5.
GPUCopyExternalImageSourceInfo
"GPUCopyExternalImageSourceInfo"
は "source" の「info」を
"copyExternalImageToTexture()"操作で記述します。
typedef (ImageBitmap or ImageData or HTMLImageElement or HTMLVideoElement or VideoFrame or HTMLCanvasElement or OffscreenCanvas );GPUCopyExternalImageSource dictionary GPUCopyExternalImageSourceInfo {required GPUCopyExternalImageSource source ;GPUOrigin2D origin = {};boolean flipY =false ; };
GPUCopyExternalImageSourceInfo
には以下のメンバーがあります:
source, 型 GPUCopyExternalImageSource-
テクセルコピーのソース。 コピー元データは
copyExternalImageToTexture()発行時点でキャプチャされます。ソースサイズは外部ソース寸法の表に従って決まります。 origin, 型 GPUOrigin2D、デフォルト値{}-
コピーの原点(コピー元サブ領域の最小(左上)コーナー)。
copySizeと合わせてコピーサブ領域全体を定義します。 flipY, 型 boolean、デフォルト値false-
ソース画像が垂直方向に反転されるか否かを記述します。
このオプションが
trueの場合、コピーは上下逆転されます(ソース領域の最下行がコピー先領域の最初の行になる等)。originオプションは依然としてソース画像の左上基準で、下方向に増加します。
外部ソースをテクスチャの作成やコピー時に使う場合、外部ソース寸法 はソースタイプごとに以下の表で定義されます:
11.2.6. サブルーチン
引数:
-
GPUTexelCopyTextureInfotexelCopyTextureInfo
戻り値: GPUExtent3D
texelCopyTextureInfoのGPUTexelCopyTextureInfo物理サブリソースサイズは以下のように算出されます:
そのwidth、height、depthOrArrayLayersはそれぞれ、
texelCopyTextureInfo.texture
のサブリソースの
物理ミップレベル固有テクスチャ範囲の
幅、高さ、深さ(ミップマップレベル
texelCopyTextureInfo.mipLevel)。
引数:
GPUTexelCopyBufferLayoutlayout-
リニアテクスチャデータのレイアウト。
GPUSize64byteSize-
リニアデータの合計サイズ(バイト単位)。
GPUTextureFormatformat-
テクスチャのフォーマット。
GPUExtent3DcopyExtent-
コピーするテクスチャの範囲。
デバイスタイムラインの手順:
-
以下を定義:
-
widthInBlocks = copyExtent.width ÷ formatのテクセルブロック幅。 Assert これは整数であること。
-
heightInBlocks = copyExtent.height ÷ formatのテクセルブロック高さ。 Assert これは整数であること。
-
bytesInLastRow = widthInBlocks × formatのテクセルブロックコピーのフットプリント。
-
-
以下の入力検証要件を満たさない場合は失敗:
-
heightInBlocks > 1の場合、 layout.
bytesPerRowを指定しなければならない。 -
copyExtent.depthOrArrayLayers > 1の場合、 layout.
bytesPerRowと layout.rowsPerImageを指定しなければならない。 -
指定されている場合、layout.
bytesPerRow≥ bytesInLastRowでなければならない。 -
指定されている場合、layout.
rowsPerImage≥ heightInBlocksでなければならない。
-
-
以下を定義:
-
bytesPerRow = layout.
bytesPerRow?? 0。 -
rowsPerImage = layout.
rowsPerImage?? 0。
注: これらのデフォルト値は常に0倍されるため効果はありません。
-
-
requiredBytesInCopy = 0とする。
-
copyExtent.depthOrArrayLayers > 0の場合:
-
requiredBytesInCopyに bytesPerRow × rowsPerImage × (copyExtent.depthOrArrayLayers − 1) を加算する。
-
heightInBlocks > 0の場合:
-
requiredBytesInCopyに bytesPerRow × (heightInBlocks − 1) + bytesInLastRow を加算する。
-
-
-
以下の条件を満たさない場合は失敗:
-
レイアウトがリニアデータ内に収まること: layout.
offset+ requiredBytesInCopy ≤ byteSize
-
引数:
GPUTexelCopyTextureInfotexelCopyTextureInfo-
コピー先のテクスチャサブリソースとコピー原点。
GPUExtent3DcopySize-
テクスチャのサイズ。
デバイスタイムラインの手順:
-
blockWidth = texelCopyTextureInfo.
texture.formatのテクセルブロック幅とする。 -
blockHeight = texelCopyTextureInfo.
texture.formatのテクセルブロック高さとする。 -
subresourceSize = texelCopyTextureInfoのGPUTexelCopyTextureInfo物理サブリソースサイズとする。
-
以下すべての条件が満たされているか判定して返す:
-
(texelCopyTextureInfo.
origin.x + copySize.width) ≤ subresourceSize.width -
(texelCopyTextureInfo.
origin.y + copySize.height) ≤ subresourceSize.height -
(texelCopyTextureInfo.
origin.z + copySize.depthOrArrayLayers) ≤ subresourceSize.depthOrArrayLayers -
copySize.widthがblockWidthの倍数であること。
-
copySize.heightがblockHeightの倍数であること。
注: テクスチャコピー範囲は物理(切り上げ)サイズで検証されるため 圧縮フォーマットの場合、 テクスチャ内に完全に収まらないブロックへのコピーも可能です。
-
GPUTextureFormat
format1とformat2は
コピー互換であるのは以下の場合:
-
format1がformat2と等しい場合、または
-
format1とformat2が、
srgbフォーマット(-srgb接尾辞の有無)のみが異なる場合。
texture
のサブリソースのうち、各サブリソースsが以下を満たす部分集合とする:
12. コマンドバッファ
コマンドバッファは、GPUコマンド(キュータイムラインのステップブロック)の事前記録リストであり、
GPUQueueに送信して実行できます。
各GPUコマンドは、
キュータイムライン上で実行される作業(状態設定、描画、リソースコピーなど)を表します。
GPUCommandBuffer
は一度しか送信できず、送信時に無効化されます。
複数回送信で描画コマンドを再利用したい場合は、GPURenderBundleを利用してください。
12.1. GPUCommandBuffer
[Exposed =(Window ,Worker ),SecureContext ]interface GPUCommandBuffer { };GPUCommandBuffer includes GPUObjectBase ;
GPUCommandBuffer
には以下のデバイスタイムラインプロパティがあります:
[[command_list]], 型 list<GPUコマンド>, 読み取り専用[[renderState]], 型 RenderState, 初期値null-
実行中のレンダーパスコマンドに使用される現在の状態。
12.1.1. コマンドバッファ生成
dictionary :GPUCommandBufferDescriptor GPUObjectDescriptorBase { };
13. コマンドエンコード
13.1. GPUCommandsMixin
GPUCommandsMixin
は、コマンドをエンコードするすべてのインターフェイスに共通する状態を定義します。
メソッドはありません。
interface mixin GPUCommandsMixin { };
GPUCommandsMixin
には以下のデバイスタイムラインプロパティがあります:
[[state]], 型 エンコーダ状態, 初期値 "open"-
エンコーダの現在の状態。
[[commands]], 型 list<GPUコマンド>, 初期値[]-
このコマンドを含む
GPUCommandBufferが送信されたとき キュータイムラインで実行されるリストのGPUコマンドです。
エンコーダ状態は以下のいずれかです:
- "open"
-
エンコーダは新しいコマンドのエンコードに利用可能です。
- "locked"
-
エンコーダは子エンコーダによってロックされているため利用できません: これは
GPUCommandEncoderであり、GPURenderPassEncoderまたはGPUComputePassEncoderがアクティブな場合です。 パスが終了すると、エンコーダは再び"open"になります。この状態でコマンドを発行すると、エンコーダを無効化します。
- "ended"
-
エンコーダは終了しており、新しいコマンドはエンコードできません。
この状態でコマンドを発行すると、検証エラーを生成します。
GPUCommandsMixin
encoderについて以下のデバイスタイムライン手順を実行:
GPUCommandsMixin
encoder
がGPUコマンドcommandのステップを発行する場合、以下のデバイスタイムライン手順を実行:
-
Append command を encoder.
[[commands]]に追加。 -
commandが
GPUCommandBufferの一部として実行される場合:-
commandのステップを実行する。
-
13.2. GPUCommandEncoder
[Exposed =(Window ,Worker ),SecureContext ]interface GPUCommandEncoder {GPURenderPassEncoder beginRenderPass (GPURenderPassDescriptor descriptor );GPUComputePassEncoder beginComputePass (optional GPUComputePassDescriptor descriptor = {});undefined copyBufferToBuffer (GPUBuffer ,source GPUBuffer ,destination optional GPUSize64 );size undefined copyBufferToBuffer (GPUBuffer source ,GPUSize64 sourceOffset ,GPUBuffer destination ,GPUSize64 destinationOffset ,optional GPUSize64 size );undefined copyBufferToTexture (GPUTexelCopyBufferInfo source ,GPUTexelCopyTextureInfo destination ,GPUExtent3D copySize );undefined copyTextureToBuffer (GPUTexelCopyTextureInfo source ,GPUTexelCopyBufferInfo destination ,GPUExtent3D copySize );undefined copyTextureToTexture (GPUTexelCopyTextureInfo source ,GPUTexelCopyTextureInfo destination ,GPUExtent3D copySize );undefined clearBuffer (GPUBuffer buffer ,optional GPUSize64 offset = 0,optional GPUSize64 size );undefined resolveQuerySet (GPUQuerySet querySet ,GPUSize32 firstQuery ,GPUSize32 queryCount ,GPUBuffer destination ,GPUSize64 destinationOffset );GPUCommandBuffer finish (optional GPUCommandBufferDescriptor descriptor = {}); };GPUCommandEncoder includes GPUObjectBase ;GPUCommandEncoder includes GPUCommandsMixin ;GPUCommandEncoder includes GPUDebugCommandsMixin ;
13.2.1. コマンドエンコーダ生成
dictionary :GPUCommandEncoderDescriptor GPUObjectDescriptorBase { };
createCommandEncoder(descriptor)-
GPUCommandEncoderを生成します。呼び出し対象:GPUDevicethis.引数:
GPUDevice.createCommandEncoder(descriptor) メソッドの引数。 パラメータ 型 Nullable Optional 説明 descriptorGPUCommandEncoderDescriptor✘ ✔ 作成する GPUCommandEncoderの記述。戻り値:
GPUCommandEncoderコンテンツタイムライン手順:
-
e を ! 新しいWebGPUオブジェクトを生成(this,
GPUCommandEncoder, descriptor)とする。 -
thisのデバイスタイムラインで初期化手順を実行する。
-
eを返す。
デバイスタイムライン 初期化手順: -
GPUCommandEncoder
を生成し、バッファのクリアコマンドをエンコードし、
エンコーダをfinishしてGPUCommandBuffer
を取得し、GPUQueueに送信する例。
const commandEncoder= gpuDevice. createCommandEncoder(); commandEncoder. clearBuffer( buffer); const commandBuffer= commandEncoder. finish(); gpuDevice. queue. submit([ commandBuffer]);
13.3. パスエンコード
beginRenderPass(descriptor)-
descriptorで記述されたレンダーパスのエンコードを開始します。
呼び出し対象:GPUCommandEncoderthis。引数:
GPUCommandEncoder.beginRenderPass(descriptor) メソッドの引数。 パラメータ 型 Nullable Optional 説明 descriptorGPURenderPassDescriptor✘ ✘ 生成する GPURenderPassEncoderの記述。戻り値:
GPURenderPassEncoderコンテンツタイムライン手順:
-
descriptor.
colorAttachmentsの各非nullなcolorAttachmentについて:-
colorAttachment.
clearValueが提供されていれば:-
GPUColor形状の検証(colorAttachment.
clearValue) を実行。
-
-
-
新しい
GPURenderPassEncoderオブジェクトpassを生成する。 -
thisのデバイスタイムラインで初期化手順を実行。
-
passを返す。
デバイスタイムライン 初期化手順:-
エンコーダ状態の検証をthisに対して実行。falseならpassを無効化して返す。
-
attachmentRegionsを空のリストとして用意。3Dテクスチャ用にdepthSliceも含む。
-
descriptor.
colorAttachmentsの各非nullなcolorAttachmentについて:-
[colorAttachment.
view, colorAttachment.depthSlice?? null] をattachmentRegionsに追加。 -
colorAttachment.
resolveTargetがnullでない場合:-
[colorAttachment.
resolveTarget, undefined] をattachmentRegionsに追加。
-
-
-
次の要件を満たしていなければpassを無効化して返す。
-
descriptorがValid Usage規則を満たすこと。
-
attachmentRegionsのテクスチャ領域は互いに重ならないこと。
-
-
attachmentRegions内の各texture subresourceをpass.
[[usage scope]]にusage=attachmentで追加。 -
depthStencilAttachment = descriptor.
depthStencilAttachmentとする。 -
depthStencilAttachmentがnullでなければ:
-
depthStencilView = depthStencilAttachment.
viewとする。 -
depthのみのsubresourceをpass.
[[usage scope]]にdepthReadOnlyならattachment-read、それ以外はattachmentで追加。 -
stencilのみのsubresourceをpass.
[[usage scope]]にstencilReadOnlyならattachment-read、それ以外はattachmentで追加。 -
pass.
[[depthReadOnly]]= depthStencilAttachment.depthReadOnlyとする。 -
pass.
[[stencilReadOnly]]= depthStencilAttachment.stencilReadOnlyとする。
-
-
pass.
[[layout]]= パスからレンダーターゲットのレイアウトを導出(descriptor)。 -
descriptor.
timestampWritesが提供されていれば:-
timestampWrites = descriptor.
timestampWritesとする。 -
timestampWrites.
beginningOfPassWriteIndexが提供されていれば、this.[[commands]]に以下のGPUコマンドを追加:-
パスコマンドの実行前に、現在のキュータイムスタンプを timestampWrites.
beginningOfPassWriteIndexに書き込む。
-
-
timestampWrites.
endOfPassWriteIndexが提供されていれば、pass.[[endTimestampWrite]]に以下のGPUコマンドを設定:-
パスコマンドの実行後に、現在のキュータイムスタンプを timestampWrites.
endOfPassWriteIndexに書き込む。
-
-
-
pass.
[[drawCount]]= 0に設定。 -
pass.
[[maxDrawCount]]= descriptor.maxDrawCountに設定。 -
pass.
[[maxDrawCount]]= descriptor.maxDrawCountに設定。 -
thisにコマンドのエンキューを行い、以降の手順をキュータイムラインで実行する。
キュータイムライン手順:-
現在実行中の
[[renderState]]を新しいRenderStateにする。 -
[[renderState]].[[colorAttachments]]= descriptor.colorAttachmentsに設定。 -
[[renderState]].[[depthStencilAttachment]]= descriptor.depthStencilAttachmentに設定。 -
descriptor.
colorAttachmentsの各非nullなcolorAttachmentについて:-
colorView = colorAttachment.
viewとする。 -
colorView.
[[descriptor]].dimensionが"3d"ならcolorSubregion = colorAttachment.depthSlice、それ以外はcolorView。 -
colorAttachment.
loadOpが"load"ならcolorSubregionの内容をframebuffer memoryにロードする。"clear"ならframebuffer memoryのすべてのtexelをcolorAttachment.
clearValueで初期化する。
-
-
depthStencilAttachmentがnullでなければ:
-
depthStencilAttachment.
depthLoadOpが未指定ならdepthReadOnlyがtrueであることをAssertし、depthのsubresource内容をframebuffer memoryにロードする。"load"ならdepthのsubresource内容をframebuffer memoryにロードする。
"clear"ならframebuffer memoryの全texelをdepthClearValueで初期化する。
-
depthStencilAttachment.
stencilLoadOpが未指定ならstencilReadOnlyがtrueであることをAssertし、stencilのsubresource内容をframebuffer memoryにロードする。"load"ならstencilのsubresource内容をframebuffer memoryにロードする。
"clear"ならframebuffer memoryの全texelをstencilClearValueで初期化する。
-
注: Read-only depth-stencilアタッチメントは暗黙的に"load"操作として扱われます。read-onlyアタッチメントにはloadOp未指定である必要があるという検証はGPURenderPassDepthStencilAttachment Valid Usageで行われます。
-
beginComputePass(descriptor)-
descriptorで記述されたコンピュートパスのエンコードを開始します。
呼び出し対象:GPUCommandEncoderthis。引数:
GPUCommandEncoder.beginComputePass(descriptor) メソッドの引数。 パラメータ 型 Nullable Optional 説明 descriptorGPUComputePassDescriptor✘ ✔ コンテンツタイムライン手順:
-
新しい
GPUComputePassEncoderオブジェクトpassを生成する。 -
thisのデバイスタイムラインで初期化手順を実行。
-
passを返す。
デバイスタイムライン 初期化手順:-
エンコーダ状態の検証をthisに対して実行。falseならpassを無効化して返す。
-
次の要件を満たしていなければpassを無効化して返す。
-
descriptor.
timestampWritesが提供されていれば:timestampWritesの検証(this.[[device]], descriptor.timestampWrites) がtrueを返すこと。
-
-
descriptor.
timestampWritesが提供されていれば:-
timestampWrites = descriptor.
timestampWritesとする。 -
timestampWrites.
beginningOfPassWriteIndexが提供されていれば、this.[[commands]]に以下のGPUコマンドを追加:-
パスコマンドの実行前に、現在のキュータイムスタンプを timestampWrites.
beginningOfPassWriteIndexに書き込む。
-
-
timestampWrites.
endOfPassWriteIndexが提供されていれば、pass.[[endTimestampWrite]]に以下のGPUコマンドを設定:-
パスコマンドの実行後に、現在のキュータイムスタンプを timestampWrites.
endOfPassWriteIndexに書き込む。
-
-
-
13.4. バッファコピーコマンド
copyBufferToBuffer() は2つのオーバーロードがあります:
copyBufferToBuffer(source, destination, size)-
省略記法であり、
copyBufferToBuffer(source, 0, destination, 0, size)と同等です。 copyBufferToBuffer(source, sourceOffset, destination, destinationOffset, size)-
GPUCommandEncoderに、あるGPUBufferのサブ領域から別のGPUBufferのサブ領域へデータをコピーするコマンドをエンコードします。呼び出し対象:GPUCommandEncoderthis。引数:
GPUCommandEncoder.copyBufferToBuffer(source, sourceOffset, destination, destinationOffset, size) メソッドの引数。 パラメータ 型 Nullable Optional 説明 sourceGPUBuffer✘ ✘ コピー元の GPUBuffer。sourceOffsetGPUSize64✘ ✘ コピー開始位置(コピー元バッファのバイトオフセット)。 destinationGPUBuffer✘ ✘ コピー先の GPUBuffer。destinationOffsetGPUSize64✘ ✘ コピー先バッファのバイトオフセット。 sizeGPUSize64✘ ✔ コピーするバイト数。 戻り値:
undefinedコンテンツタイムライン手順:
-
this.
[[device]]のデバイスタイムラインで以降の手順を実行。
デバイスタイムライン手順:-
エンコーダ状態の検証をthisに対して実行。falseなら返す。
-
sizeが
undefinedなら、source.size− sourceOffsetに設定。 -
次の条件を満たしていなければ、thisを無効化して返す。
-
thisにコマンドのエンキューを行い、以降の手順を
キュータイムラインで実行。
キュータイムライン手順:-
sourceOffsetから始まるsourceのsizeバイトを、destinationOffsetから始まるdestinationにコピーする。
-
clearBuffer(buffer, offset, size)-
GPUCommandEncoderに、GPUBufferのサブ領域をゼロ埋めするコマンドをエンコードします。呼び出し対象:GPUCommandEncoderthis。引数:
GPUCommandEncoder.clearBuffer(buffer, offset, size) メソッドの引数。 パラメータ 型 Nullable Optional 説明 bufferGPUBuffer✘ ✘ クリアする GPUBuffer。offsetGPUSize64✘ ✔ クリア領域の開始バイトオフセット。 sizeGPUSize64✘ ✔ クリアするバイト数。デフォルトは buffer のサイズ - offset。 戻り値:
undefinedコンテンツタイムライン手順:
-
this.
[[device]]のデバイスタイムラインで以降の手順を実行。
デバイスタイムライン手順:-
エンコーダ状態の検証をthisに対して実行。falseなら返す。
-
sizeが未指定の場合、
max(0, buffer.に設定。size- offset) -
次の条件を満たしていなければ、thisを無効化して返す。
-
thisにコマンドのエンキューを行い、以降の手順を
キュータイムラインで実行。
キュータイムライン手順:-
offsetから始まるbufferのsizeバイトを0に初期化する。
-
13.5. テクセルコピーコマンド
copyBufferToTexture(source, destination, copySize)-
GPUCommandEncoderに、GPUBufferのサブ領域から1つまたは複数の連続したテクスチャサブリソースのサブ領域へデータをコピーするコマンドをエンコードします。呼び出し対象:GPUCommandEncoderthis。引数:
GPUCommandEncoder.copyBufferToTexture(source, destination, copySize) メソッドの引数。 パラメータ 型 Nullable Optional 説明 sourceGPUTexelCopyBufferInfo✘ ✘ copySizeと組み合わせて、コピー元バッファの領域を定義します。 destinationGPUTexelCopyTextureInfo✘ ✘ copySizeと組み合わせて、コピー先テクスチャサブリソースの領域を定義します。 copySizeGPUExtent3D✘ ✘ 戻り値:
undefinedコンテンツタイムライン手順:
-
GPUOrigin3D形状の検証(destination.
origin) を実行。 -
GPUExtent3D形状の検証(copySize) を実行。
-
this.
[[device]]のデバイスタイムラインで以降の手順を実行。
デバイスタイムライン手順:-
エンコーダ状態の検証をthisに対して実行。falseなら返す。
-
aligned = trueとする。
-
次の条件を満たしていなければ、thisを無効化して返す。
-
GPUTexelCopyBufferInfoの検証(source) がtrueを返すこと。
-
テクスチャバッファコピーの検証(destination, source, dataLength, copySize,
COPY_DST, aligned) がtrueを返すこと。
-
-
thisにコマンドのエンキューを行い、以降の手順を
キュータイムラインで実行。
キュータイムライン手順:-
blockWidth = destination.
textureのテクセルブロック幅。 -
blockHeight = destination.
textureのテクセルブロック高さ。 -
dstOrigin = destination.
origin。 -
dstBlockOriginX = (dstOrigin.x ÷ blockWidth)。
-
dstBlockOriginY = (dstOrigin.y ÷ blockHeight)。
-
blockColumns = (copySize.width ÷ blockWidth)。
-
blockRows = (copySize.height ÷ blockHeight)。
-
dstBlockOriginX, dstBlockOriginY, blockColumns, blockRowsが整数であることをAssert。
-
z = 0 から copySize.depthOrArrayLayers - 1 まで繰り返し:
-
dstSubregion = テクスチャコピーサブ領域(z + dstOrigin.z) of destination。
-
y = 0 から blockRows - 1 まで繰り返し:
-
x = 0 から blockColumns - 1 まで繰り返し:
-
blockOffset = テクセルブロックバイトオフセット(source, (x, y, z), destination.
texture)。 -
dstSubregionの(dstBlockOriginX + x, dstBlockOriginY + y)テクセルブロックに、source.
bufferのblockOffsetの内容を同等のテクセル表現として書き込む。
-
-
-
-
copyTextureToBuffer(source, destination, copySize)-
GPUCommandEncoderに、1つまたは複数の連続したテクスチャサブリソースのサブ領域からGPUBufferのサブ領域へデータをコピーするコマンドをエンコードします。呼び出し対象:GPUCommandEncoderthis。引数:
GPUCommandEncoder.copyTextureToBuffer(source, destination, copySize) メソッドの引数。 パラメータ 型 Nullable Optional 説明 sourceGPUTexelCopyTextureInfo✘ ✘ copySizeと組み合わせて、コピー元テクスチャサブリソースの領域を定義します。 destinationGPUTexelCopyBufferInfo✘ ✘ copySizeと組み合わせて、コピー先バッファの領域を定義します。 copySizeGPUExtent3D✘ ✘ 戻り値:
undefinedコンテンツタイムライン手順:
-
GPUOrigin3D形状の検証(source.
origin) を実行。 -
GPUExtent3D形状の検証(copySize) を実行。
-
this.
[[device]]のデバイスタイムラインで以降の手順を実行。
デバイスタイムライン手順:-
エンコーダ状態の検証をthisに対して実行。falseなら返す。
-
aligned = trueとする。
-
次の条件を満たしていなければ、thisを無効化して返す。
-
GPUTexelCopyBufferInfoの検証(destination) がtrueを返すこと。
-
テクスチャバッファコピーの検証(source, destination, dataLength, copySize,
COPY_SRC, aligned) がtrueを返すこと。
-
-
thisにコマンドのエンキューを行い、以降の手順を
キュータイムラインで実行。
キュータイムライン手順:-
blockWidth = source.
textureのテクセルブロック幅。 -
blockHeight = source.
textureのテクセルブロック高さ。 -
srcOrigin = source.
origin。 -
srcBlockOriginX = (srcOrigin.x ÷ blockWidth)。
-
srcBlockOriginY = (srcOrigin.y ÷ blockHeight)。
-
blockColumns = (copySize.width ÷ blockWidth)。
-
blockRows = (copySize.height ÷ blockHeight)。
-
srcBlockOriginX, srcBlockOriginY, blockColumns, blockRowsが整数であることをAssert。
-
z = 0 から copySize.depthOrArrayLayers - 1 まで繰り返し:
-
srcSubregion = テクスチャコピーサブ領域(z + srcOrigin.z) of source。
-
y = 0 から blockRows - 1 まで繰り返し:
-
x = 0 から blockColumns - 1 まで繰り返し:
-
blockOffset = テクセルブロックバイトオフセット(destination, (x, y, z), source.
texture)。 -
destination.
bufferのblockOffsetに、srcSubregionの(srcBlockOriginX + x, srcBlockOriginY + y)テクセルブロックの同等のテクセル表現を書き込む。
-
-
-
-
copyTextureToTexture(source, destination, copySize)-
GPUCommandEncoderに、1つまたは複数の連続したテクスチャサブリソースのサブ領域から、他の1つまたは複数の連続したテクスチャサブリソースのサブ領域へデータをコピーするコマンドをエンコードします。呼び出し対象:GPUCommandEncoderthis。引数:
GPUCommandEncoder.copyTextureToTexture(source, destination, copySize) メソッドの引数。 パラメータ 型 Nullable Optional 説明 sourceGPUTexelCopyTextureInfo✘ ✘ copySizeと組み合わせて、コピー元テクスチャサブリソースの領域を定義します。 destinationGPUTexelCopyTextureInfo✘ ✘ copySizeと組み合わせて、コピー先テクスチャサブリソースの領域を定義します。 copySizeGPUExtent3D✘ ✘ 戻り値:
undefinedコンテンツタイムライン手順:
-
GPUOrigin3D形状の検証(source.
origin) を実行。 -
GPUOrigin3D形状の検証(destination.
origin) を実行。 -
GPUExtent3D形状の検証(copySize) を実行。
-
this.
[[device]]のデバイスタイムラインで以降の手順を実行。
デバイスタイムライン手順:-
エンコーダ状態の検証をthisに対して実行。falseなら返す。
-
次の条件を満たしていなければ、thisを無効化して返す。
-
srcTexture = source.
textureとする。 -
dstTexture = destination.
textureとする。 -
GPUTexelCopyTextureInfoの検証(source, copySize) がtrueを返すこと。
-
GPUTexelCopyTextureInfoの検証(destination, copySize) がtrueを返すこと。
-
srcTexture.
sampleCountがdstTexture.sampleCountと等しいこと。 -
srcTexture.
formatがデプスステンシルフォーマットの場合: -
テクスチャコピーのサブリソース集合(source, copySize)と テクスチャコピーのサブリソース集合(destination, copySize)が互いに重ならないこと。
-
-
thisにコマンドのエンキューを行い、以降の手順を
キュータイムラインで実行。
キュータイムライン手順:-
blockWidth = source.
textureのテクセルブロック幅。 -
blockHeight = source.
textureのテクセルブロック高さ。 -
srcOrigin = source.
origin。 -
srcBlockOriginX = (srcOrigin.x ÷ blockWidth)。
-
srcBlockOriginY = (srcOrigin.y ÷ blockHeight)。
-
dstOrigin = destination.
origin。 -
dstBlockOriginX = (dstOrigin.x ÷ blockWidth)。
-
dstBlockOriginY = (dstOrigin.y ÷ blockHeight)。
-
blockColumns = (copySize.width ÷ blockWidth)。
-
blockRows = (copySize.height ÷ blockHeight)。
-
srcBlockOriginX, srcBlockOriginY, dstBlockOriginX, dstBlockOriginY, blockColumns, blockRowsが整数であることをAssert。
-
z = 0 から copySize.depthOrArrayLayers - 1 まで繰り返し:
-
srcSubregion = テクスチャコピーサブ領域(z + srcOrigin.z) of source。
-
dstSubregion = テクスチャコピーサブ領域(z + dstOrigin.z) of destination。
-
y = 0 から blockRows - 1 まで繰り返し:
-
x = 0 から blockColumns - 1 まで繰り返し:
-
dstSubregionの(dstBlockOriginX + x, dstBlockOriginY + y)テクセルブロックに、srcSubregionの(srcBlockOriginX + x, srcBlockOriginY + y)テクセルブロックの同等のテクセル表現を書き込む。
-
-
-
-
13.6. クエリ
resolveQuerySet(querySet, firstQuery, queryCount, destination, destinationOffset)-
GPUQuerySetのクエリ結果をGPUBufferの範囲に書き出すコマンドをGPUCommandEncoderにエンコードします。呼び出し対象:GPUCommandEncoderthis。引数:
GPUCommandEncoder.resolveQuerySet(querySet, firstQuery, queryCount, destination, destinationOffset) メソッドの引数。 パラメータ 型 Nullable Optional 説明 querySetGPUQuerySet✘ ✘ firstQueryGPUSize32✘ ✘ queryCountGPUSize32✘ ✘ destinationGPUBuffer✘ ✘ destinationOffsetGPUSize64✘ ✘ 戻り値:
undefinedコンテンツタイムライン手順:
-
this.
[[device]]のデバイスタイムラインで以降の手順を実行。
デバイスタイムライン手順:-
エンコーダ状態の検証をthisに対して実行。falseなら返す。
-
次の条件を満たしていなければ、thisを無効化して返す。
-
querySetがthisで有効に使用可能であること。
-
destinationがthisで有効に使用可能であること。
-
destination.
usageにQUERY_RESOLVEが含まれること。 -
firstQuery < querySetのクエリ数。
-
(firstQuery + queryCount) ≤ querySetのクエリ数。
-
destinationOffsetが256の倍数であること。
-
destinationOffset + 8 × queryCount ≤ destination.
sizeであること。
-
-
thisにコマンドのエンキューを行い、以降の手順を
キュータイムラインで実行。
キュータイムライン手順:-
queryIndex = firstQueryとする。
-
offset = destinationOffsetとする。
-
queryIndex < firstQuery + queryCountの間繰り返し:
-
destinationのoffsetから8バイトに、querySetのqueryIndex番目の値を書き込む。
-
queryIndex = queryIndex + 1とする。
-
offset = offset + 8とする。
-
-
13.7. ファイナライズ
GPUCommandBuffer
に、GPUCommandEncoder
で記録されたコマンドを含めるには、
finish()
を呼び出します。
finish()
が呼び出されると、
そのコマンドエンコーダはこれ以上使用できなくなります。
finish(descriptor)-
コマンド列の記録を完了し、対応する
GPUCommandBufferを返します。呼び出し対象:GPUCommandEncoderthis。引数:
GPUCommandEncoder.finish(descriptor) メソッドの引数。 パラメータ 型 Nullable Optional 説明 descriptorGPUCommandBufferDescriptor✘ ✔ 戻り値:
GPUCommandBufferコンテンツタイムライン手順:
-
commandBufferを新しい
GPUCommandBufferとして定義。 -
this.
[[device]]のデバイスタイムラインでfinish手順を実行。 -
commandBufferを返す。
デバイスタイムライン finish手順:-
以下すべての条件が満たされていればvalidationSucceeded=true、そうでなければfalse。
-
thisが有効であること。
-
this.
[[debug_group_stack]]が空であること。
-
-
validationSucceededがfalseなら:
-
無効化された
GPUCommandBufferを返す。
-
commandBuffer.
[[command_list]]にthis.[[commands]]を設定。
-
14. プログラマブルパス
interface mixin {GPUBindingCommandsMixin undefined setBindGroup (GPUIndex32 index ,GPUBindGroup ?bindGroup ,optional sequence <GPUBufferDynamicOffset >dynamicOffsets = []);undefined setBindGroup (GPUIndex32 index ,GPUBindGroup ?bindGroup , [AllowShared ]Uint32Array dynamicOffsetsData ,GPUSize64 dynamicOffsetsDataStart ,GPUSize32 dynamicOffsetsDataLength ); };
GPUBindingCommandsMixin
は同じオブジェクト上に
GPUObjectBase
と GPUCommandsMixin
のメンバーが存在することを前提としています。
これらのミックスインも含むインターフェイスのみがGPUBindingCommandsMixinをincludeできます。
GPUBindingCommandsMixin
には以下のデバイスタイムラインプロパティがあります:
[[bind_groups]], 型 ordered map<GPUIndex32,GPUBindGroup>, 初期値は空-
各インデックスに対する現在の
GPUBindGroup。 [[dynamic_offsets]], 型 ordered map<GPUIndex32, list<GPUBufferDynamicOffset>>, 初期値は空-
各
[[bind_groups]]エントリに対する現在のダイナミックオフセット。
14.1. バインドグループ
setBindGroup() には2つのオーバーロードがあります:
setBindGroup(index, bindGroup, dynamicOffsets)-
指定したインデックスに対する現在の
GPUBindGroupを設定します。呼び出し対象:GPUBindingCommandsMixinthis。引数:
index, 型GPUIndex32, 非null, 必須-
バインドグループを設定するインデックス。
bindGroup, 型GPUBindGroup, nullable, 必須-
以降のレンダー/コンピュートコマンドで使用するバインドグループ。
dynamicOffsets, 型 sequence<GPUBufferDynamicOffset>, 非null, デフォルトは[]-
bindGroup内で
buffer.hasDynamicOffsetがtrueとなっている各エントリのバイト単位オフセット配列。順序はGPUBindGroupLayoutEntry.bindingで決まる。詳細は注参照。
戻り値:
undefinedコンテンツタイムライン手順:
-
this.
[[device]]のデバイスタイムラインで以降の手順を実行。
デバイスタイムライン手順:-
エンコーダ状態の検証をthisに対して実行。falseなら返す。
-
bindGroupがnullならdynamicOffsetCountは0、nullでなければbindGroup.
[[layout]].[[dynamicOffsetCount]]。 -
次の要件を満たしていなければthisを無効化して返す。
-
index < this.
[[device]].[[limits]].maxBindGroupsであること。 -
dynamicOffsets.sizeがdynamicOffsetCountと等しいこと。
-
-
bindGroupがnullの場合:
それ以外の場合:
-
次の要件を満たしていなければthisを無効化して返す。
-
bindGroupがthisで有効に使用可能であること。
-
各ダイナミックバインディング (bufferBinding, bufferLayout, dynamicOffsetIndex) in bindGroup:
-
bufferBinding.
offset+ dynamicOffsets[dynamicOffsetIndex] + bufferLayout.minBindingSize≤ bufferBinding.buffer.sizeであること。 -
bufferLayout.
typeが"uniform"の場合:-
dynamicOffsetが
minUniformBufferOffsetAlignmentの倍数であること。
-
-
bufferLayout.
typeが"storage"または"read-only-storage"の場合:-
dynamicOffsetが
minStorageBufferOffsetAlignmentの倍数であること。
-
-
-
-
this.
[[bind_groups]][index] にbindGroupをセット。 -
this.
[[dynamic_offsets]][index] にdynamicOffsetsのコピーをセット。 -
thisが
GPURenderCommandsMixinの場合:-
this.
[[bind_groups]]内の各bindGroupについて、bindGroup.[[usedResources]]をthis.[[usage scope]]にマージする。
-
-
setBindGroup(index, bindGroup, dynamicOffsetsData, dynamicOffsetsDataStart, dynamicOffsetsDataLength)-
指定したインデックスに対して現在の
GPUBindGroupを設定し、 ダイナミックオフセットをUint32Arrayの部分集合として指定します。呼び出し対象:GPUBindingCommandsMixinthis。引数:
GPUBindingCommandsMixin.setBindGroup(index, bindGroup, dynamicOffsetsData, dynamicOffsetsDataStart, dynamicOffsetsDataLength) メソッドの引数。 パラメータ 型 Nullable Optional 説明 indexGPUIndex32✘ ✘ バインドグループを設定するインデックス。 bindGroupGPUBindGroup?✔ ✘ 以降のレンダー/コンピュートコマンドで使用するバインドグループ。 dynamicOffsetsDataUint32Array✘ ✘ bindGroup内で buffer.hasDynamicOffsetがtrueとなっている各エントリのバイト単位オフセット配列。順序はGPUBindGroupLayoutEntry.bindingによる。詳細は注参照。dynamicOffsetsDataStartGPUSize64✘ ✘ dynamicOffsetsDataの要素オフセット(バイトオフセットではない)。 dynamicOffsetsDataLengthGPUSize32✘ ✘ dynamicOffsetsDataから読み込むバッファオフセット数。 戻り値:
undefinedコンテンツタイムライン手順:
-
次の要件を満たしていなければ、
RangeErrorをthrowして返す。-
dynamicOffsetsDataStart >= 0であること。
-
dynamicOffsetsDataStart + dynamicOffsetsDataLength ≤ dynamicOffsetsData.
lengthであること。
-
-
dynamicOffsetsをdynamicOffsetsDataのdynamicOffsetsDataStart番目からdynamicOffsetsDataLength要素分、コピーしたリストとする。
-
this.
setBindGroup(index, bindGroup, dynamicOffsets)を呼び出す。
-
GPUBindGroupLayoutEntry.binding
の順序で適用されます。
つまり、dynamic bindingsが GPUBindGroupLayoutEntry
のうち GPUBindGroupLayout
内で buffer?.hasDynamicOffset
が true となっているものを GPUBindGroupLayoutEntry.binding順にソートしたリストとすると、
setBindGroup()に渡す
dynamic offset[i] は
dynamic bindings[i] に対応します。
GPUBindGroupLayoutの場合:
// 配列内のbindingsは順序が異なっていますが、 // binding indexでソートされるため順序は問題ありません。 let layout= gpuDevice. createBindGroupLayout({ entries: [{ binding: 1 , buffer: {}, }, { binding: 2 , buffer: { dynamicOffset: true }, }, { binding: 0 , buffer: { dynamicOffset: true }, }] });
次の呼び出しで生成されたGPUBindGroupを使用する場合:
// 上記同様、配列順序はここでも関係ありません。 // レイアウトで使われた順序と一致する必要もありません。 let bindGroup= gpuDevice. createBindGroup({ layout: layout, entries: [{ binding: 1 , resource: { buffer: bufferA, offset: 256 }, }, { binding: 2 , resource: { buffer: bufferB, offset: 512 }, }, { binding: 0 , resource: { buffer: bufferC}, }] });
次の呼び出しでバインドする場合:
pass. setBindGroup( 0 , bindGroup, [ 1024 , 2048 ]);
各バッファオフセットの適用結果:
| Binding | Buffer | Offset |
|---|---|---|
| 0 | bufferC | 1024 (ダイナミック) |
| 1 | bufferA | 256 (静的) |
| 2 | bufferB | 2560 (静的 + ダイナミック) |
GPUBindGroup
bindGroupについて、各ダイナミックオフセットに対して実行するstepsのリストで、以下のデバイスタイムライン手順を実行:
-
dynamicOffsetIndex = 0とする。
-
layout = bindGroup.
[[layout]]とする。 -
bindGroup.
[[entries]]内の各GPUBindGroupEntryentryについて、entry.bindingの昇順で:-
bindingDescriptor = layout.
[[entryMap]][entry.binding]とする。 -
bindingDescriptor.
buffer?.hasDynamicOffsetがtrueの場合:-
bufferBinding = get as buffer binding(entry.
resource)。 -
bufferLayout = bindingDescriptor.
buffer。 -
steps(bufferBinding, bufferLayout, dynamicOffsetIndex) を呼び出す。
-
dynamicOffsetIndex = dynamicOffsetIndex + 1とする。
-
-
引数:
GPUBindingCommandsMixinencoder-
検証対象のバインドグループを持つエンコーダ。
GPUPipelineBasepipeline-
encoderのバインドグループが互換性を持つべきパイプライン。
デバイスタイムライン手順:
-
以下のいずれかの条件が満たされていなければ、falseを返す:
-
pipelineはnullでないこと。
-
パイプラインで使用される全てのバインドグループが設定され、かつパイプラインレイアウトと互換性があること: pipeline.
[[layout]].[[bindGroupLayouts]]内の各(index, bindGroupLayout)について:-
bindGroupLayoutがnullの場合、continue。
-
bindGroup = encoder.
[[bind_groups]][index]。 -
dynamicOffsets = encoder.
[[dynamic_offsets]][index]。 -
bindGroupはnullでないこと。
-
bindGroup.
[[layout]]がbindGroupLayoutとgroup-equivalentであること。 -
dynamicOffsetIndex = 0とする。
-
bindGroup.
[[entries]]の各bindGroupEntryについて、bindGroupEntry.binding順に:-
bindGroupLayoutEntry = bindGroup.
[[layout]].[[entryMap]][bindGroupEntry.binding]。 -
bindGroupLayoutEntry.
bufferが提供されていなければcontinue。 -
bound = get as buffer binding(bindGroupEntry.
resource)。 -
bindGroupLayoutEntry.
buffer.hasDynamicOffsetの場合:-
bound.
offsetにdynamicOffsets[dynamicOffsetIndex]を加算。 -
dynamicOffsetIndexを1増やす。
-
-
bindGroupEntry.
[[prevalidatedSize]]がfalseの場合:-
effective buffer binding size(bound)が、パイプラインのシェーダ内でbindGroupEntryに対応するバインディング変数のminimum buffer binding size以上であること。
-
-
-
-
エンコーダのバインドグループが書き込み可能なリソースとエイリアスしていないこと(encoder, pipeline)がfalseであること。
-
それ以外の場合はtrueを返す。
GPUTextureView
オブジェクトの可能性あり)。
注: このアルゴリズムはusage scope storage exceptionの使用を制限します。
引数:
GPUBindingCommandsMixinencoder-
検証対象のバインドグループを持つエンコーダ。
GPUPipelineBasepipeline-
encoderのバインドグループが互換性を持つべきパイプライン。
デバイスタイムライン手順:
-
stage in [
VERTEX,FRAGMENT,COMPUTE]について:-
bufferBindings = (
GPUBufferBinding,boolean)のリストとする。booleanはリソースが書き込み可能かどうか。 -
textureViews = (
GPUTextureView,boolean)のリストとする。booleanはリソースが書き込み可能かどうか。 -
pipeline.
[[layout]].[[bindGroupLayouts]]内の各(bindGroupIndex, bindGroupLayout)について:-
bindGroup = encoder.
[[bind_groups]][bindGroupIndex]。 -
bindGroupLayoutEntries = bindGroupLayout.
[[descriptor]].entries。 -
bufferRanges = bindGroupのバッファ範囲(ダイナミックオフセットはencoder.
[[dynamic_offsets]][bindGroupIndex]を使用) -
bufferRanges内の各(bindGroupLayoutEntry, resource)で、bindGroupLayoutEntry.
visibilityがstageを含む場合:-
resourceWritable = (bindGroupLayoutEntry.
buffer.type== "storage")。 -
bufferBindings内の各(pastResource, pastResourceWritable)について:
-
resourceWritableまたはpastResourceWritableがtrueで、pastResourceとresourceがbuffer-binding-aliasingならtrueを返す。
-
-
(resource, resourceWritable)をbufferBindingsに追加。
-
-
bindGroupLayoutEntries内の各bindGroupLayoutEntryと対応するbindGroup内のresource(GPUTextureView)で、bindGroupLayoutEntry.
visibilityがstageを含む場合:-
bindGroupLayoutEntry.
storageTextureが提供されていなければcontinue。 -
resourceWritable = bindGroupLayoutEntry.
storageTexture.accessが書き込み可能なアクセスモードかどうか。 -
textureViews内の各(pastResource, pastResourceWritable)について:
-
resourceWritableまたはpastResourceWritableがtrueで、pastResourceとresourceがtexture-view-aliasingならtrueを返す。
-
-
(resource, resourceWritable)をtextureViewsに追加。
-
-
-
-
falseを返す。
注: 実装者はこのアルゴリズムの最適化を強く推奨します。
15. デバッグマーカー
GPUDebugCommandsMixinは、コマンドグループにデバッグラベルを適用したり、コマンド列に単一ラベルを挿入したりするためのメソッドを提供します。
デバッググループは入れ子にして、ラベル付きコマンドの階層を作ることができ、バランスが取れていなければなりません。
オブジェクトラベルと同様、これらのラベルには必須の動作はありませんが、エラーメッセージやブラウザ開発者ツールに表示されたり、ネイティブAPIバックエンドに渡されたりする場合があります。
interface mixin GPUDebugCommandsMixin {undefined pushDebugGroup (USVString groupLabel );undefined popDebugGroup ();undefined insertDebugMarker (USVString markerLabel ); };
GPUDebugCommandsMixin
は同じオブジェクト上に
GPUObjectBase
と GPUCommandsMixin
のメンバーが存在することを前提としています。
これらのミックスインも含むインターフェイスのみがGPUDebugCommandsMixinをincludeできます。
GPUDebugCommandsMixin
には以下のデバイスタイムラインプロパティがあります:
[[debug_group_stack]], 型 stack<USVString>-
アクティブなデバッググループラベルのスタック。
GPUDebugCommandsMixin
には以下のメソッドがあります:
pushDebugGroup(groupLabel)-
以降のコマンドを含むラベル付きデバッググループを開始します。
呼び出し対象:GPUDebugCommandsMixinthis。引数:
GPUDebugCommandsMixin.pushDebugGroup(groupLabel) メソッドの引数。 パラメータ 型 Nullable Optional 説明 groupLabelUSVString✘ ✘ コマンドグループのラベル。 戻り値:
undefinedコンテンツタイムライン手順:
-
this.
[[device]]のデバイスタイムラインで以降の手順を実行。
デバイスタイムライン手順:-
エンコーダ状態の検証をthisに対して実行。falseなら返す。
-
groupLabelをthis.
[[debug_group_stack]]にpushする。
-
popDebugGroup()-
直近に
pushDebugGroup()で開始したラベル付きデバッググループを終了します。呼び出し対象:GPUDebugCommandsMixinthis。戻り値:
undefinedコンテンツタイムライン手順:
-
this.
[[device]]のデバイスタイムラインで以降の手順を実行。
デバイスタイムライン手順:-
エンコーダ状態の検証をthisに対して実行。falseなら返す。
-
次の要件を満たしていなければthisを無効化して返す。
-
this.
[[debug_group_stack]]が空でないこと。
-
-
insertDebugMarker(markerLabel)-
コマンドストリームの任意の位置にラベルを挿入します。
呼び出し対象:GPUDebugCommandsMixinthis。引数:
GPUDebugCommandsMixin.insertDebugMarker(markerLabel) メソッドの引数。 パラメータ 型 Nullable Optional 説明 markerLabelUSVString✘ ✘ 挿入するラベル。 戻り値:
undefinedコンテンツタイムライン手順:
-
this.
[[device]]のデバイスタイムラインで以降の手順を実行。
デバイスタイムライン手順:-
エンコーダ状態の検証をthisに対して実行。falseなら返す。
-
16. コンピュートパス
16.1. GPUComputePassEncoder
[Exposed =(Window ,Worker ),SecureContext ]interface GPUComputePassEncoder {undefined setPipeline (GPUComputePipeline pipeline );undefined dispatchWorkgroups (GPUSize32 workgroupCountX ,optional GPUSize32 workgroupCountY = 1,optional GPUSize32 workgroupCountZ = 1);undefined dispatchWorkgroupsIndirect (GPUBuffer indirectBuffer ,GPUSize64 indirectOffset );undefined end (); };GPUComputePassEncoder includes GPUObjectBase ;GPUComputePassEncoder includes GPUCommandsMixin ;GPUComputePassEncoder includes GPUDebugCommandsMixin ;GPUComputePassEncoder includes GPUBindingCommandsMixin ;
GPUComputePassEncoder
には以下のデバイスタイムラインプロパティがあります:
[[command_encoder]], 型GPUCommandEncoder, 読み取り専用-
このコンピュートパスエンコーダを生成した
GPUCommandEncoder。 [[endTimestampWrite]], 型 GPU command?, 読み取り専用, デフォルトはnull-
パス終了時にタイムスタンプを書き込むGPUコマンド(ある場合)。
[[pipeline]], 型GPUComputePipeline, 初期値はnull
16.1.1. コンピュートパスエンコーダ生成
dictionary {GPUComputePassTimestampWrites required GPUQuerySet querySet ;GPUSize32 beginningOfPassWriteIndex ;GPUSize32 endOfPassWriteIndex ; };
querySet, 型 GPUQuerySet-
クエリ結果を書き込む
GPUQuerySet。 型は"timestamp"。 beginningOfPassWriteIndex, 型 GPUSize32-
指定された場合、computeパス開始時のタイムスタンプを書き込む
querySet内のクエリインデックス。 endOfPassWriteIndex, 型 GPUSize32-
指定された場合、computeパス終了時のタイムスタンプを書き込む
querySet内のクエリインデックス。
注: タイムスタンプクエリ値はナノ秒単位で書き込まれますが、その値の決定方法は実装依存であり、必ずしも単調増加するとは限りません。詳細は§ 20.4 Timestamp Queryを参照してください。
dictionary :GPUComputePassDescriptor GPUObjectDescriptorBase {GPUComputePassTimestampWrites timestampWrites ; };
timestampWrites, 型 GPUComputePassTimestampWrites-
このパスでどのタイムスタンプ値を書き込み、どこに書き込むかを定義します。
16.1.2. ディスパッチ
setPipeline(pipeline)-
現在の
GPUComputePipelineを設定します。呼び出し対象:GPUComputePassEncoderthis。引数:
GPUComputePassEncoder.setPipeline(pipeline) メソッドの引数。 パラメータ 型 Nullable Optional 説明 pipelineGPUComputePipeline✘ ✘ 以降のディスパッチコマンドで使用するコンピュートパイプライン。 戻り値:
undefinedコンテンツタイムライン手順:
-
this.
[[device]]のデバイスタイムラインで以降の手順を実行。
デバイスタイムライン手順:-
エンコーダ状態の検証をthisに対して実行。falseなら返す。
-
次の条件を満たしていなければthisを無効化して返す。
-
pipelineがthisで有効に使用可能であること。
-
-
this.
[[pipeline]]にpipelineをセットする。
-
dispatchWorkgroups(workgroupCountX, workgroupCountY, workgroupCountZ)-
現在の
GPUComputePipelineで実行する作業をディスパッチします。 詳細な仕様は§ 23.1 コンピューティングを参照。呼び出し対象:GPUComputePassEncoderthis。引数:
GPUComputePassEncoder.dispatchWorkgroups(workgroupCountX, workgroupCountY, workgroupCountZ) メソッドの引数。 パラメータ 型 Nullable Optional 説明 workgroupCountXGPUSize32✘ ✘ ディスパッチするワークグループのX次元。 workgroupCountYGPUSize32✘ ✔ ディスパッチするワークグループのY次元。 workgroupCountZGPUSize32✘ ✔ ディスパッチするワークグループのZ次元。 注:x,y,zの値はdispatchWorkgroups()およびdispatchWorkgroupsIndirect()に渡すものであり、各次元でディスパッチするワークグループ数であって、各次元で実行するシェーダ呼び出しの数ではありません。これは現代のネイティブGPU APIの挙動と一致していますが、OpenCLとは異なります。例えば
GPUShaderModuleのエントリポイントが@workgroup_size(4, 4)で、computePass.dispatchWorkgroups(8, 8);を呼び出した場合、エントリポイントは合計1024回呼ばれます。X軸・Y軸両方で4x4のワークグループを8回ずつディスパッチするためです(4*4*8*8=1024)。戻り値:
undefinedコンテンツタイムライン手順:
-
this.
[[device]]のデバイスタイムラインで以降の手順を実行。
デバイスタイムライン手順:-
エンコーダ状態の検証をthisに対して実行。falseなら返す。
-
usageScopeを空のusage scopeとする。
-
this.
[[bind_groups]]内の各bindGroupについて、bindGroup.[[usedResources]]をusageScopeにマージする。 -
次の条件を満たしていなければ、thisを無効化して返す。
-
usageScopeがusage scope validationを満たすこと。
-
エンコーダのバインドグループの検証(this, this.
[[pipeline]])がtrueであること。 -
workgroupCountX, workgroupCountY, workgroupCountZのすべてがthis.device.limits.
maxComputeWorkgroupsPerDimension以下であること。
-
-
bindingStateをthisの現在の状態のスナップショットとする。
-
thisにコマンドのエンキューを行い、以降の手順をキュータイムラインで実行。
キュータイムライン手順:-
[workgroupCountX, workgroupCountY, workgroupCountZ]次元のワークグループグリッドを、bindingState.
[[pipeline]]とbindingState.[[bind_groups]]を用いて実行する。
-
dispatchWorkgroupsIndirect(indirectBuffer, indirectOffset)-
現在の
GPUComputePipelineで、GPUBufferからパラメータを読み取って作業をディスパッチします。 詳細な仕様は§ 23.1 コンピューティング参照。バッファ内のindirect dispatch parametersは、32ビット符号なし整数3つ(合計12バイト)を引数順(
dispatchWorkgroups()の引数順)に詰めて格納します。例:let dispatchIndirectParameters= new Uint32Array( 3 ); dispatchIndirectParameters[ 0 ] = workgroupCountX; dispatchIndirectParameters[ 1 ] = workgroupCountY; dispatchIndirectParameters[ 2 ] = workgroupCountZ; 呼び出し対象:GPUComputePassEncoderthis。引数:
GPUComputePassEncoder.dispatchWorkgroupsIndirect(indirectBuffer, indirectOffset) メソッドの引数。 パラメータ 型 Nullable Optional 説明 indirectBufferGPUBuffer✘ ✘ indirect dispatch parametersを格納するバッファ。 indirectOffsetGPUSize64✘ ✘ indirectBuffer内でディスパッチデータが始まるバイトオフセット。 戻り値:
undefinedコンテンツタイムライン手順:
-
this.
[[device]]のデバイスタイムラインで以降の手順を実行。
デバイスタイムライン手順:-
エンコーダ状態の検証をthisに対して実行。falseなら返す。
-
usageScopeを空のusage scopeとする。
-
this.
[[bind_groups]]内の各bindGroupについて、bindGroup.[[usedResources]]をusageScopeにマージする。 -
indirectBufferをusageScopeにusageで追加する。
-
次の条件を満たしていなければ、thisを無効化して返す。
-
usageScopeがusage scope validationを満たすこと。
-
エンコーダのバインドグループの検証(this, this.
[[pipeline]])がtrueであること。 -
indirectBufferがthisで有効に使用可能であること。
-
indirectOffset + sizeof(indirect dispatch parameters) ≤ indirectBuffer.
sizeであること。 -
indirectOffsetが4の倍数であること。
-
-
bindingStateをthisの現在の状態のスナップショットとする。
-
thisにコマンドのエンキューを行い、以降の手順をキュータイムラインで実行。
キュータイムライン手順:-
workgroupCountX = indirectBufferのindirectOffsetバイト目から符号なし32ビット整数値として読み取る。
-
workgroupCountY = indirectBufferの(indirectOffset + 4)バイト目から符号なし32ビット整数値として読み取る。
-
workgroupCountZ = indirectBufferの(indirectOffset + 8)バイト目から符号なし32ビット整数値として読み取る。
-
workgroupCountX, workgroupCountY, workgroupCountZのいずれかがthis.device.limits.
maxComputeWorkgroupsPerDimensionを超えていればreturn。 -
[workgroupCountX, workgroupCountY, workgroupCountZ]次元のワークグループグリッドを、bindingState.
[[pipeline]]とbindingState.[[bind_groups]]を用いて実行する。
-
16.1.3. ファイナライズ
ユーザーがパスのコマンド記録を完了したら end()
を呼び出すことでコンピュートパスエンコーダを終了できます。end()
が呼び出されると、コンピュートパスエンコーダはそれ以降使用できません。
end()-
コンピュートパスコマンド列の記録を完了します。
呼び出し対象:GPUComputePassEncoderthis。戻り値:
undefinedコンテンツタイムライン手順:
-
this.
[[device]]のデバイスタイムラインで以降の手順を実行。
デバイスタイムライン手順:-
parentEncoder = this.
[[command_encoder]]とする。 -
次の要件を満たしていなければ検証エラーを生成してreturn。
-
次の要件を満たしていなければparentEncoderを無効化してreturn。
-
thisが有効であること。
-
this.
[[debug_group_stack]]が空であること。
-
-
parentEncoder.
[[commands]]にthis.[[commands]]をExtendする。 -
this.
[[endTimestampWrite]]がnullでない場合:-
parentEncoder.
[[commands]]にthis.[[endTimestampWrite]]をExtendする。
-
-
17. レンダーパス
17.1. GPURenderPassEncoder
[Exposed =(Window ,Worker ),SecureContext ]interface GPURenderPassEncoder {undefined setViewport (float x ,float y ,float width ,float height ,float minDepth ,float maxDepth );undefined setScissorRect (GPUIntegerCoordinate x ,GPUIntegerCoordinate y ,GPUIntegerCoordinate width ,GPUIntegerCoordinate height );undefined setBlendConstant (GPUColor color );undefined setStencilReference (GPUStencilValue reference );undefined beginOcclusionQuery (GPUSize32 queryIndex );undefined endOcclusionQuery ();undefined executeBundles (sequence <GPURenderBundle >bundles );undefined end (); };GPURenderPassEncoder includes GPUObjectBase ;GPURenderPassEncoder includes GPUCommandsMixin ;GPURenderPassEncoder includes GPUDebugCommandsMixin ;GPURenderPassEncoder includes GPUBindingCommandsMixin ;GPURenderPassEncoder includes GPURenderCommandsMixin ;
GPURenderPassEncoder
には以下のデバイスタイムラインプロパティがあります:
[[command_encoder]], 型GPUCommandEncoder, 読み取り専用-
このレンダーパスエンコーダを生成した
GPUCommandEncoder。 [[attachment_size]], 読み取り専用-
次の範囲に設定される:
-
width, height= パスのレンダーアタッチメントのサイズ
-
[[occlusion_query_set]], 型GPUQuerySet, 読み取り専用-
パス内のオクルージョンクエリ結果を書き込む
GPUQuerySet。パス生成時にGPURenderPassDescriptor.occlusionQuerySetで初期化される。 [[endTimestampWrite]], 型 GPUコマンド?、読み取り専用、 デフォルトはnull-
パス終了時にタイムスタンプを書き込むGPUコマンド(ある場合)。
[[maxDrawCount]]型GPUSize64, 読み取り専用-
このパスで許可される最大ドロー数。
[[occlusion_query_active]], 型boolean-
パスの
[[occlusion_query_set]]が書き込まれているかどうか。
エンコードされたレンダーパスコマンドがGPUCommandBufferの一部として実行されるとき、
内部的にRenderStateオブジェクトがレンダリングに必要な現在の状態を管理するために使用されます。
RenderStateには以下のキュータイムラインプロパティがあります:
[[occlusionQueryIndex]], 型GPUSize32-
オクルージョンクエリ結果を書き込む
[[occlusion_query_set]]内のインデックス。 [[viewport]]-
現在のビューポート矩形と深度範囲。初期値は次の通り:
-
x, y=0.0, 0.0 -
width, height= パスのレンダーターゲットのサイズ -
minDepth, maxDepth=0.0, 1.0
-
[[scissorRect]]-
現在のシザーレクト。初期値は次の通り:
-
x, y=0, 0 -
width, height= パスのレンダーターゲットのサイズ
-
[[blendConstant]], 型GPUColor-
現在のブレンド定数値。初期値は
[0, 0, 0, 0]。 [[stencilReference]], 型GPUStencilValue-
現在のステンシル参照値。初期値は
0。 [[colorAttachments]], 型 sequence<GPURenderPassColorAttachment?>-
このレンダーパスのカラーアタッチメントとその状態。
[[depthStencilAttachment]], 型GPURenderPassDepthStencilAttachment?-
このレンダーパスのデプス/ステンシルアタッチメントとその状態。
レンダーパスにはframebuffer memoryもあり、各アタッチメントに対応するテクセルデータを格納し、ドローコマンドで書き込まれたり、ブレンドやデプス/ステンシルテストで読み取られたりする。
注: GPUハードウェアによっては、framebuffer memoryがアタッチメントテクスチャで割り当てられたメモリである場合や、タイルベースアーキテクチャのようにテクスチャデータがコピーされる別領域のメモリである場合もある。
17.1.1. レンダーパスエンコーダ生成
dictionary {GPURenderPassTimestampWrites required GPUQuerySet querySet ;GPUSize32 beginningOfPassWriteIndex ;GPUSize32 endOfPassWriteIndex ; };
querySet, 型 GPUQuerySet-
クエリ結果を書き込む
GPUQuerySet。型は"timestamp"。 beginningOfPassWriteIndex, 型 GPUSize32-
指定された場合、レンダーパス開始時のタイムスタンプを書き込む
querySet内のクエリインデックス。 endOfPassWriteIndex, 型 GPUSize32-
指定された場合、レンダーパス終了時のタイムスタンプを書き込む
querySet内のクエリインデックス。
注: タイムスタンプクエリ値はナノ秒単位で書き込まれますが、その値の決定方法は実装依存であり、必ずしも単調増加するとは限りません。詳細は§ 20.4 Timestamp Queryを参照。
dictionary :GPURenderPassDescriptor GPUObjectDescriptorBase {required sequence <GPURenderPassColorAttachment ?>colorAttachments ;GPURenderPassDepthStencilAttachment depthStencilAttachment ;GPUQuerySet occlusionQuerySet ;GPURenderPassTimestampWrites timestampWrites ;GPUSize64 maxDrawCount = 50000000; };
colorAttachments, 型sequence<GPURenderPassColorAttachment?>-
このシーケンス内の
GPURenderPassColorAttachment値の集合が、このレンダーパスの実行時に出力されるカラーアタッチメントを定義します。使用互換性のため、どのカラーアタッチメントも他のアタッチメントやパス内で使われるリソースとエイリアスしてはなりません。
depthStencilAttachment, 型 GPURenderPassDepthStencilAttachment-
実行時に出力・テストされるデプス/ステンシルアタッチメントを定義する
GPURenderPassDepthStencilAttachment値。使用互換性のため、どの書き込み可能なデプス/ステンシルアタッチメントも他のアタッチメントやパス内で使われるリソースとエイリアスしてはなりません。
occlusionQuerySet, 型 GPUQuerySet-
このパスのオクルージョンクエリ結果の格納先を定義する
GPUQuerySet値。 timestampWrites, 型 GPURenderPassTimestampWrites-
このパスでどのタイムスタンプ値を書き込み、どこに書き込むかを定義します。
maxDrawCount, 型 GPUSize64、デフォルト値は50000000-
このレンダーパスで実行される最大ドロー呼び出し数。一部の実装ではレンダーパス前に投入される処理のサイズ決定に使われます。デフォルト値のままで問題ありませんが、より多くのドロー呼び出しが行われることが分かっている場合は調整してください。
GPUDevice
deviceとGPURenderPassDescriptor
thisが与えられた場合、以下の検証ルールが適用されます:
-
this.
colorAttachments.sizeは device.[[limits]].maxColorAttachments以下でなければならない。 -
this.
colorAttachments内の非nullなcolorAttachmentごとに:-
colorAttachment.
resolveTargetが提供されている場合:-
colorAttachment.
resolveTargetはdeviceで有効に使用可能でなければならない。
-
-
colorAttachmentはGPURenderPassColorAttachment 有効な使用方法のルールを満たす必要がある。
-
this.
depthStencilAttachmentが提供されている場合:-
this.
depthStencilAttachment.viewはdeviceで有効に使用可能でなければならない。 -
this.
depthStencilAttachmentはGPURenderPassDepthStencilAttachment 有効な使用方法のルールを満たす必要がある。
-
-
少なくとも1つのアタッチメントが存在しなければならない。以下のいずれか:
-
this.
colorAttachments内に非null値がある、または -
this.
depthStencilAttachmentが存在する。
-
-
GPURenderPassDescriptorのカラ―アタッチメントbytes per sampleの検証(device, this.
colorAttachments) が成功すること。 -
this.
colorAttachments内の非nullメンバーのviewおよび this.depthStencilAttachment.view(あれば)は、同じsampleCountでなければならない。 -
this.
colorAttachments内の非nullメンバーのviewおよび this.depthStencilAttachment.view(あれば)は、[[renderExtent]]が一致していなければならない。 -
this.
occlusionQuerySetが提供されている場合:-
this.
occlusionQuerySetはdeviceで有効に使用可能でなければならない。 -
this.
occlusionQuerySet.typeはocclusionでなければならない。
-
-
this.
timestampWritesが提供されている場合:-
timestampWritesの検証(device, this.
timestampWrites) がtrueを返すこと。
-
引数:
-
GPUDevicedevice -
sequence<
GPURenderPassColorAttachment?> colorAttachments
デバイスタイムライン手順:
-
formatsを空のlist<
GPUTextureFormat?>とする。 -
colorAttachments内のcolorAttachmentごとに:
-
colorAttachmentがundefinedならcontinue。
-
formatsに追加 colorAttachment.
view.[[descriptor]].formatを。
-
-
formatsのカラ―アタッチメントbytes per sampleの計算が device.
[[limits]].maxColorAttachmentBytesPerSample以下でなければならない。
17.1.1.1. カラ―アタッチメント
dictionary {GPURenderPassColorAttachment required (GPUTexture or GPUTextureView )view ;GPUIntegerCoordinate depthSlice ; (GPUTexture or GPUTextureView )resolveTarget ;GPUColor clearValue ;required GPULoadOp loadOp ;required GPUStoreOp storeOp ; };
view, 型(GPUTexture または GPUTextureView)-
このカラ―アタッチメントで出力されるテクスチャサブリソースを記述します。 サブリソースはget as texture view(
view)呼び出しで決定されます。 depthSlice, 型 GPUIntegerCoordinateresolveTarget, 型(GPUTexture または GPUTextureView)-
このカラ―アタッチメントがマルチサンプルの場合、解決された出力を受け取るテクスチャサブリソースを記述します。 サブリソースはget as texture view(
resolveTarget)呼び出しで決定されます。 clearValue, 型 GPUColor-
レンダーパス実行前に
viewをクリアする値を示します。指定されていない場合は{r: 0, g: 0, b: 0, a: 0}がデフォルトです。loadOpが"clear"でない場合は無視されます。clearValueの各成分はdouble値です。 レンダーアタッチメントに合ったテクスチャフォーマットのテクセル値へ変換されます。 変換に失敗した場合、バリデーションエラーが生成されます。 loadOp, 型 GPULoadOp-
レンダーパス実行前に
viewに対して行うロード操作を示します。注: クリアを推奨します。詳細は
"clear"を参照してください。 storeOp, 型 GPUStoreOp-
レンダーパス実行後に
viewに対して行うストア操作。
GPURenderPassColorAttachment
thisが与えられた場合:
-
renderViewDescriptor = this.
view.[[descriptor]]とする。 -
renderTexture = this.
view.[[texture]]とする。 -
以下の手順の要件をすべて満たさなければならない。
-
renderViewDescriptor.
formatはカラ―レンダラブルフォーマットでなければならない。 -
this.
viewはレンダラブルテクスチャビューでなければならない。 -
renderViewDescriptor.
dimensionが"3d"の場合:-
this.
depthSliceが指定されているかつ depthOrArrayLayers未満であること (renderTextureの論理的mipレベル別テクスチャ範囲 のrenderViewDescriptor. baseMipLevel)。
それ以外の場合:
-
this.
depthSliceは指定されていてはならない。
-
-
-
IDL値this.
clearValueの renderViewDescriptor.formatへのテクセル値変換はTypeErrorを投げてはならない。注: フォーマットの範囲外でも対応するWGSLプリミティブ型(
f32,i32,u32)の範囲内ならエラーは発生しません。
-
-
this.
resolveTargetが指定されている場合:-
resolveViewDescriptor = this.
resolveTarget.[[descriptor]]とする。 -
resolveTexture = this.
resolveTarget.[[texture]]とする。 -
renderTexture.
sampleCountは1より大きくなければならない。 -
resolveTexture.
sampleCountは1でなければならない。 -
this.
resolveTargetは非3dのレンダラブルテクスチャビューでなければならない。 -
this.
resolveTarget.[[renderExtent]]および this.view.[[renderExtent]]が一致していなければならない。 -
resolveViewDescriptor.
formatは renderViewDescriptor.formatと等しくなければならない。 -
resolveViewDescriptor.
formatは§ 26.1.1 プレーンカラーフォーマットに従いresolve可能でなければならない。
-
-
GPUTextureView
viewはレンダラブルテクスチャビュー
となります。以下のデバイスタイムライン手順のすべての要件を満たす場合:
-
descriptor = view.
[[descriptor]]とする。 -
descriptor.
usageにRENDER_ATTACHMENTが含まれていなければならない。 -
descriptor.
dimensionは"2d"または"2d-array"または"3d"でなければならない。 -
descriptor.
mipLevelCountは1でなければならない。 -
descriptor.
arrayLayerCountは1でなければならない。 -
descriptor.
aspectがview.[[texture]]のすべてのアスペクトを参照していなければならない。
引数:
-
sequence<
GPUTextureFormat?> formats
戻り値: GPUSize32
-
total = 0とする。
-
formats内の非nullformatごとに
-
Assert: formatはカラ―レンダラブルフォーマットである。
-
renderTargetPixelByteCost = formatのレンダーターゲットピクセルバイトコスト。
-
renderTargetComponentAlignment = formatのレンダーターゲットコンポーネントアライメント。
-
totalをrenderTargetComponentAlignmentの倍数になるように切り上げる。
-
renderTargetPixelByteCostをtotalに加算する。
-
-
totalを返す。
17.1.1.2. デプス/ステンシルアタッチメント
dictionary {GPURenderPassDepthStencilAttachment required (GPUTexture or GPUTextureView )view ;float depthClearValue ;GPULoadOp depthLoadOp ;GPUStoreOp depthStoreOp ;boolean depthReadOnly =false ;GPUStencilValue stencilClearValue = 0;GPULoadOp stencilLoadOp ;GPUStoreOp stencilStoreOp ;boolean stencilReadOnly =false ; };
view, 型(GPUTexture または GPUTextureView)-
このデプス/ステンシルアタッチメントで出力・読み取りされるテクスチャサブリソースを記述します。 サブリソースはget as texture view(
view)呼び出しで決定されます。 depthClearValue, 型 float-
レンダーパス実行前に
viewのデプス成分をクリアする値を示します。depthLoadOpが"clear"でない場合は無視されます。 0.0以上1.0以下でなければなりません。 depthLoadOp, 型 GPULoadOp-
レンダーパス実行前に
viewのデプス成分に対して行うロード操作を示します。注: クリアを推奨します。詳細は
"clear"を参照してください。 depthStoreOp, 型 GPUStoreOp-
レンダーパス実行後に
viewのデプス成分に対して行うストア操作。 depthReadOnly, 型 boolean, デフォルトはfalse-
viewのデプス成分が読み取り専用であることを示します。 stencilClearValue, 型 GPUStencilValue, デフォルトは0-
レンダーパス実行前に
viewのステンシル成分をクリアする値を示します。stencilLoadOpが"clear"でない場合は無視されます。値はviewのステンシルアスペクトの型に変換され、1テクセル分のステンシルアスペクトビット数分のLSBを利用します。
stencilLoadOp, 型 GPULoadOp-
レンダーパス実行前に
viewのステンシル成分に対して行うロード操作を示します。注: クリアを推奨します。詳細は
"clear"を参照してください。 stencilStoreOp, 型 GPUStoreOp-
レンダーパス実行後に
viewのステンシル成分に対して行うストア操作。 stencilReadOnly, 型 boolean, デフォルトはfalse-
viewのステンシル成分が読み取り専用であることを示します。
GPURenderPassDepthStencilAttachment
thisが与えられた場合、以下のバリデーションルールが適用されます:
-
this.
viewはデプスまたはステンシルフォーマットでなければならない。 -
this.
viewはレンダラブルテクスチャビューでなければならない。 -
format = this.
view.[[descriptor]].formatとする。 -
this.
depthLoadOpが"clear"の場合、 this.depthClearValueが指定されていて、かつ0.0以上1.0以下でなければならない。 -
formatがデプスアスペクトを持ち、this.
depthReadOnlyがfalseの場合:-
this.
depthLoadOpが指定されていなければならない。 -
this.
depthStoreOpが指定されていなければならない。
それ以外の場合:
-
this.
depthLoadOpは指定されていてはならない。 -
this.
depthStoreOpは指定されていてはならない。
-
-
formatがステンシルアスペクトを持ち、this.
stencilReadOnlyがfalseの場合:-
this.
stencilLoadOpが指定されていなければならない。 -
this.
stencilStoreOpが指定されていなければならない。
それ以外の場合:
-
this.
stencilLoadOpは指定されていてはならない。 -
this.
stencilStoreOpは指定されていてはならない。
-
17.1.1.3. ロード/ストア操作
enum {GPULoadOp "load" ,"clear" , };
"load"-
このアタッチメントの既存の値をレンダーパスにロードします。
"clear"-
このアタッチメントのクリア値をレンダーパスにロードします。
注: 一部のGPUハードウェア(主にモバイル)では、
"clear"の方がはるかに高速です。これは、メインメモリからタイルローカルメモリへのデータロードを回避できるためです。 他のGPUハードウェアでは大きな違いはありません。そのため、初期値が重要でない場合(例:レンダーターゲットをスカイボックスでクリアする場合)は"clear"を"load"よりも推奨します。
enum {GPUStoreOp "store" ,"discard" , };
"store"-
レンダーパスの実行結果をこのアタッチメントに保存します。
"discard"-
レンダーパスの実行結果をこのアタッチメントで破棄します。
注: 破棄されたアタッチメントはゼロクリアされたかのように扱われますが、実装はレンダーパス終了時に明示的なクリアを行う必要はありません。 パス終了時に明示的なクリアを行わない実装は、アタッチメントの内容を読み込む(サンプリング、コピー、次のレンダーパスへ
"load"でアタッチ、キャンバス表示や読み出し (get a copy of the image contents of a context) など)前に遅延クリアを行わなければなりません。
17.1.1.4. レンダーパスレイアウト
GPURenderPassLayout
はGPURenderBundleのレンダーターゲットのレイアウトを宣言します。
また、内部的には
GPURenderPassEncoder
のレイアウトや
GPURenderPipeline
のレイアウトにも使われます。
この型は、レンダーパス・レンダーバンドル・レンダーパイプライン間の互換性判定に使われます。
dictionary :GPURenderPassLayout GPUObjectDescriptorBase {required sequence <GPUTextureFormat ?>colorFormats ;GPUTextureFormat depthStencilFormat ;GPUSize32 sampleCount = 1; };
colorFormats, 型sequence<GPUTextureFormat?>-
このパスまたはバンドルのカラ―アタッチメントの
GPUTextureFormatのリスト。 depthStencilFormat, 型 GPUTextureFormat-
このパスまたはバンドルのデプス/ステンシルアタッチメントの
GPUTextureFormat。 sampleCount, 型 GPUSize32, デフォルトは1-
このパスまたはバンドルのアタッチメントのピクセルごとのサンプル数。
GPURenderPassLayout
値は等しいのは:
-
それぞれの
depthStencilFormatとsampleCountが等しいこと、かつ -
それぞれの
colorFormatsが末尾のnullを無視して等しいこと。
引数:
-
GPURenderPassDescriptordescriptor
戻り値: GPURenderPassLayout
デバイスタイムライン手順:
-
layoutを新しい
GPURenderPassLayoutオブジェクトとする。 -
descriptor.
colorAttachments内のcolorAttachmentごとに:-
colorAttachmentがnullでない場合:
-
layout.
sampleCountにcolorAttachment.view.[[texture]].sampleCountをセットする。 -
layout.
colorFormatsにcolorAttachment.view.[[descriptor]].formatを追加する。
-
-
それ以外の場合:
-
layout.
colorFormatsにnullを追加する。
-
-
-
depthStencilAttachment = descriptor.
depthStencilAttachmentとする。 -
depthStencilAttachmentがnullでない場合:
-
view = depthStencilAttachment.
viewとする。 -
layout.
sampleCountにview.[[texture]].sampleCountをセットする。 -
layout.
depthStencilFormatにview.[[descriptor]].formatをセットする。
-
-
layoutを返す。
引数:
-
GPURenderPipelineDescriptordescriptor
戻り値: GPURenderPassLayout
デバイスタイムライン手順:
-
layoutを新しい
GPURenderPassLayoutオブジェクトとする。 -
layout.
sampleCountにdescriptor.multisample.countをセットする。 -
descriptor.
depthStencilが指定されている場合:-
layout.
depthStencilFormatにdescriptor.depthStencil.formatをセットする。
-
-
descriptor.
fragmentが指定されている場合:-
descriptor.
fragment.targets内のcolorTargetごとに:-
colorTargetがnullでなければlayout.
colorFormatsにcolorTarget.formatを追加、nullであればnullを追加。
-
-
-
layoutを返す。
17.1.2. ファイナライズ
レンダーパスのコマンド記録が完了したら、end()
を呼び出すことでレンダーパスエンコーダを終了できます。end()
が呼び出された後は、このレンダーパスエンコーダは使用できません。
end()-
レンダーパスコマンド列の記録を完了します。
呼び出し対象:GPURenderPassEncoderthis。戻り値:
undefinedコンテンツタイムライン手順:
-
this.
[[device]]のデバイスタイムラインで以降の手順を実行。
デバイスタイムライン手順:-
parentEncoder = this.
[[command_encoder]]とする。 -
以下の要件が満たされていなければ、バリデーションエラーを生成してreturn。
-
次の要件が満たされていなければparentEncoderを無効化してreturn。
-
thisが有効であること。
-
this.
[[usage scope]]がusage scope validationを満たすこと。 -
this.
[[debug_group_stack]]が空であること。 -
this.
[[occlusion_query_active]]がfalseであること。 -
this.
[[drawCount]]がthis.[[maxDrawCount]]以下であること。
-
-
parentEncoder.
[[commands]]にthis.[[commands]]をExtendする。 -
this.
[[endTimestampWrite]]がnullでない場合:-
parentEncoder.
[[commands]]にthis.[[endTimestampWrite]]をExtendする。
-
-
thisにレンダーコマンドのエンキューを行い、以降の手順をrenderState付きでキュータイムラインで実行。
キュータイムライン手順:-
renderState.
[[colorAttachments]]内の非nullcolorAttachmentごとに:-
colorView = colorAttachment.
viewとする。 -
colorView.
[[descriptor]].dimensionが:"3d"-
colorSubregion = colorAttachment.
depthSliceof colorViewとする。 - それ以外
-
colorSubregion = colorViewとする。
-
colorAttachment.
resolveTargetがnullでない場合:-
colorSubregionの各テクセルの複数サンプルを1サンプルに解決し、colorAttachment.
resolveTargetにコピーする。
-
-
colorAttachment.
storeOpが:"store"-
colorSubregionに関連付けられたフレームバッファメモリ の内容をcolorSubregionに保存する。
"discard"-
colorSubregionの各テクセルをゼロにする。
-
-
depthStencilAttachment = renderState.
[[depthStencilAttachment]]とする。 -
depthStencilAttachmentがnullでない場合:
-
depthStencilAttachment.
depthStoreOpが: -
depthStencilAttachment.
stencilStoreOpが:
-
-
renderState = nullとする。
注: 破棄されたアタッチメントはゼロクリアされたかのように扱われますが、実装はレンダーパス終了時に明示的なクリアを行う必要はありません。詳細は
"discard"の注を参照してください。注: 読み取り専用デプス・ステンシルアタッチメントは暗黙的に
"store"操作を使うものと考えられますが、パス中に内容が変更されないため実装はアタッチメントを更新する必要はありません。ストア操作を指定してはならないというバリデーションはGPURenderPassDepthStencilAttachment 有効な使用方法で行われます。 -
17.2. GPURenderCommandsMixin
GPURenderCommandsMixin
はGPURenderPassEncoder
とGPURenderBundleEncoder
に共通のレンダリングコマンドを定義します。
interface mixin GPURenderCommandsMixin {undefined setPipeline (GPURenderPipeline pipeline );undefined setIndexBuffer (GPUBuffer buffer ,GPUIndexFormat indexFormat ,optional GPUSize64 offset = 0,optional GPUSize64 size );undefined setVertexBuffer (GPUIndex32 slot ,GPUBuffer ?buffer ,optional GPUSize64 offset = 0,optional GPUSize64 size );undefined draw (GPUSize32 vertexCount ,optional GPUSize32 instanceCount = 1,optional GPUSize32 firstVertex = 0,optional GPUSize32 firstInstance = 0);undefined drawIndexed (GPUSize32 indexCount ,optional GPUSize32 instanceCount = 1,optional GPUSize32 firstIndex = 0,optional GPUSignedOffset32 baseVertex = 0,optional GPUSize32 firstInstance = 0);undefined drawIndirect (GPUBuffer indirectBuffer ,GPUSize64 indirectOffset );undefined drawIndexedIndirect (GPUBuffer indirectBuffer ,GPUSize64 indirectOffset ); };
GPURenderCommandsMixin
assumes the presence of
GPUObjectBase,
GPUCommandsMixin,
and GPUBindingCommandsMixin
members on the same object.
It must only be included by interfaces which also include those mixins.
GPURenderCommandsMixin
has the following device timeline properties:
[[layout]], of typeGPURenderPassLayout, readonly-
The layout of the render pass.
[[depthReadOnly]], of typeboolean, readonly-
If
true, indicates that the depth component is not modified. [[stencilReadOnly]], of typeboolean, readonly-
If
true, indicates that the stencil component is not modified. [[usage scope]], of type usage scope, initially empty-
The usage scope for this render pass or bundle.
[[pipeline]], of typeGPURenderPipeline, initiallynull-
The current
GPURenderPipeline. [[index_buffer]], of typeGPUBuffer, initiallynull-
The current buffer to read index data from.
[[index_format]], of typeGPUIndexFormat-
The format of the index data in
[[index_buffer]]. [[index_buffer_offset]], of typeGPUSize64-
The offset in bytes of the section of
[[index_buffer]]currently set. [[index_buffer_size]], of typeGPUSize64-
The size in bytes of the section of
[[index_buffer]]currently set, initially0. [[vertex_buffers]], of type ordered map<slot,GPUBuffer>, initially empty-
The current
GPUBuffers to read vertex data from for each slot. [[vertex_buffer_sizes]], of type ordered map<slot,GPUSize64>, initially empty-
The size in bytes of the section of
GPUBuffercurrently set for each slot. [[drawCount]], of typeGPUSize64-
The number of draw commands recorded in this encoder.
GPURenderCommandsMixin
encoder which
issues the steps of a GPU Command
command with RenderState renderState, run the
following device
timeline steps:
-
Append command to encoder.
[[commands]]. -
When command is executed as part of a
GPUCommandBuffercommandBuffer:-
Issue the steps of command with commandBuffer.
[[renderState]]as renderState.
-
17.2.1. Drawing
setPipeline(pipeline)-
Sets the current
GPURenderPipeline.Called on:GPURenderCommandsMixinthis.Arguments:
Arguments for the GPURenderCommandsMixin.setPipeline(pipeline) method. Parameter Type Nullable Optional Description pipelineGPURenderPipeline✘ ✘ The render pipeline to use for subsequent drawing commands. Returns:
undefinedContent timeline steps:
-
Issue the subsequent steps on the Device timeline of this.
[[device]].
Device timeline steps:-
Validate the encoder state of this. If it returns false, return.
-
Let pipelineTargetsLayout be derive render targets layout from pipeline(pipeline.
[[descriptor]]). -
If any of the following conditions are unsatisfied, invalidate this and return.
-
pipeline is valid to use with this.
-
this.
[[layout]]equals pipelineTargetsLayout. -
If pipeline.
[[writesDepth]]: this.[[depthReadOnly]]must befalse. -
If pipeline.
[[writesStencil]]: this.[[stencilReadOnly]]must befalse.
-
-
Set this.
[[pipeline]]to be pipeline.
-
setIndexBuffer(buffer, indexFormat, offset, size)-
Sets the current index buffer.
Called on:GPURenderCommandsMixinthis.Arguments:
Arguments for the GPURenderCommandsMixin.setIndexBuffer(buffer, indexFormat, offset, size) method. Parameter Type Nullable Optional Description bufferGPUBuffer✘ ✘ Buffer containing index data to use for subsequent drawing commands. indexFormatGPUIndexFormat✘ ✘ Format of the index data contained in buffer. offsetGPUSize64✘ ✔ Offset in bytes into buffer where the index data begins. Defaults to 0.sizeGPUSize64✘ ✔ Size in bytes of the index data in buffer. Defaults to the size of the buffer minus the offset. Returns:
undefinedContent timeline steps:
-
Issue the subsequent steps on the Device timeline of this.
[[device]].
Device timeline steps:-
Validate the encoder state of this. If it returns false, return.
-
If size is missing, set size to max(0, buffer.
size- offset). -
If any of the following conditions are unsatisfied, invalidate this and return.
-
buffer is valid to use with this.
-
offset is a multiple of indexFormat’s byte size.
-
offset + size ≤ buffer.
size.
-
-
Add buffer to
[[usage scope]]with usage input. -
Set this.
[[index_buffer]]to be buffer. -
Set this.
[[index_format]]to be indexFormat. -
Set this.
[[index_buffer_offset]]to be offset. -
Set this.
[[index_buffer_size]]to be size.
-
setVertexBuffer(slot, buffer, offset, size)-
Sets the current vertex buffer for the given slot.
Called on:GPURenderCommandsMixinthis.Arguments:
Arguments for the GPURenderCommandsMixin.setVertexBuffer(slot, buffer, offset, size) method. Parameter Type Nullable Optional Description slotGPUIndex32✘ ✘ The vertex buffer slot to set the vertex buffer for. bufferGPUBuffer?✔ ✘ Buffer containing vertex data to use for subsequent drawing commands. offsetGPUSize64✘ ✔ Offset in bytes into buffer where the vertex data begins. Defaults to 0.sizeGPUSize64✘ ✔ Size in bytes of the vertex data in buffer. Defaults to the size of the buffer minus the offset. Returns:
undefinedContent timeline steps:
-
Issue the subsequent steps on the Device timeline of this.
[[device]].
Device timeline steps:-
Validate the encoder state of this. If it returns false, return.
-
Let bufferSize be 0 if buffer is
null, or buffer.sizeif not. -
If size is missing, set size to max(0, bufferSize - offset).
-
If any of the following requirements are unmet, invalidate this and return.
-
slot must be < this.
[[device]].[[limits]].maxVertexBuffers. -
offset must be a multiple of 4.
-
offset + size must be ≤ bufferSize.
-
-
If buffer is
null:-
Remove this.
[[vertex_buffers]][slot]. -
Remove this.
[[vertex_buffer_sizes]][slot].
Otherwise:
-
If any of the following requirements are unmet, invalidate this and return.
-
buffer must be valid to use with this.
-
-
Add buffer to
[[usage scope]]with usage input. -
Set this.
[[vertex_buffers]][slot] to be buffer. -
Set this.
[[vertex_buffer_sizes]][slot] to be size.
-
-
draw(vertexCount, instanceCount, firstVertex, firstInstance)-
Draws primitives. See § 23.2 Rendering for the detailed specification.
Called on:GPURenderCommandsMixinthis.Arguments:
Arguments for the GPURenderCommandsMixin.draw(vertexCount, instanceCount, firstVertex, firstInstance) method. Parameter Type Nullable Optional Description vertexCountGPUSize32✘ ✘ The number of vertices to draw. instanceCountGPUSize32✘ ✔ The number of instances to draw. firstVertexGPUSize32✘ ✔ Offset into the vertex buffers, in vertices, to begin drawing from. firstInstanceGPUSize32✘ ✔ First instance to draw. Returns:
undefinedContent timeline steps:
-
Issue the subsequent steps on the Device timeline of this.
[[device]].
Device timeline steps:-
Validate the encoder state of this. If it returns false, return.
-
All of the requirements in the following steps must be met. If any are unmet, invalidate this and return.
-
It must be valid to draw with this.
-
Let buffers be this.
[[pipeline]].[[descriptor]].vertex.buffers. -
For each
GPUIndex32slot from0to buffers.size (non-inclusive):-
If buffers[slot] is
null, continue. -
Let bufferSize be this.
[[vertex_buffer_sizes]][slot]. -
Let stride be buffers[slot].
arrayStride. -
Let attributes be buffers[slot].
attributes -
Let lastStride be the maximum value of (attribute.
offset+ byteSize(attribute.format)) over each attribute in attributes, or 0 if attributes is empty. -
Let strideCount be computed based on buffers[slot].
stepMode:"vertex"-
firstVertex + vertexCount
"instance"-
firstInstance + instanceCount
-
If strideCount ≠
0:-
(strideCount −
1) × stride + lastStride must be ≤ bufferSize.
-
-
-
-
Increment this.
[[drawCount]]by 1. -
Let bindingState be a snapshot of this’s current state.
-
Enqueue a render command on this which issues the subsequent steps on the Queue timeline with renderState when executed.
Queue timeline steps:-
Draw instanceCount instances, starting with instance firstInstance, of primitives consisting of vertexCount vertices, starting with vertex firstVertex, with the states from bindingState and renderState.
-
drawIndexed(indexCount, instanceCount, firstIndex, baseVertex, firstInstance)-
Draws indexed primitives. See § 23.2 Rendering for the detailed specification.
Called on:GPURenderCommandsMixinthis.Arguments:
Arguments for the GPURenderCommandsMixin.drawIndexed(indexCount, instanceCount, firstIndex, baseVertex, firstInstance) method. Parameter Type Nullable Optional Description indexCountGPUSize32✘ ✘ The number of indices to draw. instanceCountGPUSize32✘ ✔ The number of instances to draw. firstIndexGPUSize32✘ ✔ Offset into the index buffer, in indices, begin drawing from. baseVertexGPUSignedOffset32✘ ✔ Added to each index value before indexing into the vertex buffers. firstInstanceGPUSize32✘ ✔ First instance to draw. Returns:
undefinedContent timeline steps:
-
Issue the subsequent steps on the Device timeline of this.
[[device]].
Device timeline steps:-
Validate the encoder state of this. If it returns false, return.
-
If any of the following conditions are unsatisfied, invalidate this and return.
-
It is valid to draw indexed with this.
-
firstIndex + indexCount ≤ this.
[[index_buffer_size]]÷ this.[[index_format]]’s byte size; -
Let buffers be this.
[[pipeline]].[[descriptor]].vertex.buffers. -
For each
GPUIndex32slot from0to buffers.size (non-inclusive):-
If buffers[slot] is
null, continue. -
Let bufferSize be this.
[[vertex_buffer_sizes]][slot]. -
Let stride be buffers[slot].
arrayStride. -
Let lastStride be max(attribute.
offset+ byteSize(attribute.format)) for each attribute in buffers[slot].attributes. -
Let strideCount be firstInstance + instanceCount.
-
If buffers[slot].
stepModeis"instance"and strideCount ≠0:-
Ensure (strideCount −
1) × stride + lastStride ≤ bufferSize.
-
-
-
-
Increment this.
[[drawCount]]by 1. -
Let bindingState be a snapshot of this’s current state.
-
Enqueue a render command on this which issues the subsequent steps on the Queue timeline with renderState when executed.
Queue timeline steps:-
Draw instanceCount instances, starting with instance firstInstance, of primitives consisting of indexCount indexed vertices, starting with index firstIndex from vertex baseVertex, with the states from bindingState and renderState.
Note: WebGPU applications should never use index data with indices out of bounds of any bound vertex buffer that has
GPUVertexStepMode"vertex". WebGPU implementations have different ways of handling this, and therefore a range of behaviors is allowed. Either the whole draw call is discarded, or the access to those attributes out of bounds is described by WGSL’s invalid memory reference. -
drawIndirect(indirectBuffer, indirectOffset)-
Draws primitives using parameters read from a
GPUBuffer. See § 23.2 Rendering for the detailed specification.The indirect draw parameters encoded in the buffer must be a tightly packed block of four 32-bit unsigned integer values (16 bytes total), given in the same order as the arguments for
draw(). For example:let drawIndirectParameters= new Uint32Array( 4 ); drawIndirectParameters[ 0 ] = vertexCount; drawIndirectParameters[ 1 ] = instanceCount; drawIndirectParameters[ 2 ] = firstVertex; drawIndirectParameters[ 3 ] = firstInstance; The value corresponding to
firstInstancemust be 0, unless the"indirect-first-instance"feature is enabled. If the"indirect-first-instance"feature is not enabled andfirstInstanceis not zero thedrawIndirect()call will be treated as a no-op.Called on:GPURenderCommandsMixinthis.Arguments:
Arguments for the GPURenderCommandsMixin.drawIndirect(indirectBuffer, indirectOffset) method. Parameter Type Nullable Optional Description indirectBufferGPUBuffer✘ ✘ Buffer containing the indirect draw parameters. indirectOffsetGPUSize64✘ ✘ Offset in bytes into indirectBuffer where the drawing data begins. Returns:
undefinedContent timeline steps:
-
Issue the subsequent steps on the Device timeline of this.
[[device]].
Device timeline steps:-
Validate the encoder state of this. If it returns false, return.
-
If any of the following conditions are unsatisfied, invalidate this and return.
-
It is valid to draw with this.
-
indirectBuffer is valid to use with this.
-
indirectOffset + sizeof(indirect draw parameters) ≤ indirectBuffer.
size. -
indirectOffset is a multiple of 4.
-
-
Add indirectBuffer to
[[usage scope]]with usage input. -
Increment this.
[[drawCount]]by 1. -
Let bindingState be a snapshot of this’s current state.
-
Enqueue a render command on this which issues the subsequent steps on the Queue timeline with renderState when executed.
Queue timeline steps:-
Let vertexCount be an unsigned 32-bit integer read from indirectBuffer at indirectOffset bytes.
-
Let instanceCount be an unsigned 32-bit integer read from indirectBuffer at (indirectOffset + 4) bytes.
-
Let firstVertex be an unsigned 32-bit integer read from indirectBuffer at (indirectOffset + 8) bytes.
-
Let firstInstance be an unsigned 32-bit integer read from indirectBuffer at (indirectOffset + 12) bytes.
-
Draw instanceCount instances, starting with instance firstInstance, of primitives consisting of vertexCount vertices, starting with vertex firstVertex, with the states from bindingState and renderState.
-
drawIndexedIndirect(indirectBuffer, indirectOffset)-
Draws indexed primitives using parameters read from a
GPUBuffer. See § 23.2 Rendering for the detailed specification.The indirect drawIndexed parameters encoded in the buffer must be a tightly packed block of five 32-bit values (20 bytes total), given in the same order as the arguments for
drawIndexed(). The value corresponding tobaseVertexis a signed 32-bit integer, and all others are unsigned 32-bit integers. For example:let drawIndexedIndirectParameters= new Uint32Array( 5 ); let drawIndexedIndirectParametersSigned= new Int32Array( drawIndexedIndirectParameters. buffer); drawIndexedIndirectParameters[ 0 ] = indexCount; drawIndexedIndirectParameters[ 1 ] = instanceCount; drawIndexedIndirectParameters[ 2 ] = firstIndex; // baseVertex is a signed value. drawIndexedIndirectParametersSigned[ 3 ] = baseVertex; drawIndexedIndirectParameters[ 4 ] = firstInstance; The value corresponding to
firstInstancemust be 0, unless the"indirect-first-instance"feature is enabled. If the"indirect-first-instance"feature is not enabled andfirstInstanceis not zero thedrawIndexedIndirect()call will be treated as a no-op.Called on:GPURenderCommandsMixinthis.Arguments:
Arguments for the GPURenderCommandsMixin.drawIndexedIndirect(indirectBuffer, indirectOffset) method. Parameter Type Nullable Optional Description indirectBufferGPUBuffer✘ ✘ Buffer containing the indirect drawIndexed parameters. indirectOffsetGPUSize64✘ ✘ Offset in bytes into indirectBuffer where the drawing data begins. Returns:
undefinedContent timeline steps:
-
Issue the subsequent steps on the Device timeline of this.
[[device]].
Device timeline steps:-
Validate the encoder state of this. If it returns false, return.
-
If any of the following conditions are unsatisfied, invalidate this and return.
-
It is valid to draw indexed with this.
-
indirectBuffer is valid to use with this.
-
indirectOffset + sizeof(indirect drawIndexed parameters) ≤ indirectBuffer.
size. -
indirectOffset is a multiple of 4.
-
-
Add indirectBuffer to
[[usage scope]]with usage input. -
Increment this.
[[drawCount]]by 1. -
Let bindingState be a snapshot of this’s current state.
-
Enqueue a render command on this which issues the subsequent steps on the Queue timeline with renderState when executed.
Queue timeline steps:-
Let indexCount be an unsigned 32-bit integer read from indirectBuffer at indirectOffset bytes.
-
Let instanceCount be an unsigned 32-bit integer read from indirectBuffer at (indirectOffset + 4) bytes.
-
Let firstIndex be an unsigned 32-bit integer read from indirectBuffer at (indirectOffset + 8) bytes.
-
Let baseVertex be a signed 32-bit integer read from indirectBuffer at (indirectOffset + 12) bytes.
-
Let firstInstance be an unsigned 32-bit integer read from indirectBuffer at (indirectOffset + 16) bytes.
-
Draw instanceCount instances, starting with instance firstInstance, of primitives consisting of indexCount indexed vertices, starting with index firstIndex from vertex baseVertex, with the states from bindingState and renderState.
-
GPURenderCommandsMixin
encoder,
run the following device
timeline steps:
-
If any of the following conditions are unsatisfied, return
false:-
Validate encoder bind groups(encoder, encoder.
[[pipeline]]) must betrue. -
Let pipelineDescriptor be encoder.
[[pipeline]].[[descriptor]]. -
For each
GPUIndex32slot0to pipelineDescriptor.vertex.buffers.size:-
If pipelineDescriptor.
vertex.buffers[slot] is notnull, encoder.[[vertex_buffers]]must contain slot.
-
-
Validate
maxBindGroupsPlusVertexBuffers:-
Let bindGroupSpaceUsed be (the maximum key in encoder.
[[bind_groups]]) + 1. -
Let vertexBufferSpaceUsed be (the maximum key in encoder.
[[vertex_buffers]]) + 1. -
bindGroupSpaceUsed + vertexBufferSpaceUsed must be ≤ encoder.
[[device]].[[limits]].maxBindGroupsPlusVertexBuffers.
-
-
-
Otherwise return
true.
GPURenderCommandsMixin
encoder,
run the following device
timeline steps:
-
If any of the following conditions are unsatisfied, return
false:-
It must be valid to draw with encoder.
-
encoder.
[[index_buffer]]must not benull. -
Let topology be encoder.
[[pipeline]].[[descriptor]].primitive.topology. -
If topology is
"line-strip"or"triangle-strip":-
encoder.
[[index_format]]must equal encoder.[[pipeline]].[[descriptor]].primitive.stripIndexFormat.
-
-
-
Otherwise return
true.
17.2.2. Rasterization state
The GPURenderPassEncoder
has several methods which affect how draw commands are rasterized to
attachments used by this encoder.
setViewport(x, y, width, height, minDepth, maxDepth)-
Sets the viewport used during the rasterization stage to linearly map from normalized device coordinates to viewport coordinates.
Called on:GPURenderPassEncoderthis.Arguments:
Arguments for the GPURenderPassEncoder.setViewport(x, y, width, height, minDepth, maxDepth) method. Parameter Type Nullable Optional Description xfloat✘ ✘ Minimum X value of the viewport in pixels. yfloat✘ ✘ Minimum Y value of the viewport in pixels. widthfloat✘ ✘ Width of the viewport in pixels. heightfloat✘ ✘ Height of the viewport in pixels. minDepthfloat✘ ✘ Minimum depth value of the viewport. maxDepthfloat✘ ✘ Maximum depth value of the viewport. Returns:
undefinedContent timeline steps:
-
Issue the subsequent steps on the Device timeline of this.
[[device]].
Device timeline steps:-
Validate the encoder state of this. If it returns false, return.
-
Let maxViewportRange be this.
limits.maxTextureDimension2D×2. -
If any of the following conditions are unsatisfied, invalidate this and return.
-
x ≥ -maxViewportRange
-
y ≥ -maxViewportRange
-
0≤ width ≤ this.limits.maxTextureDimension2D -
0≤ height ≤ this.limits.maxTextureDimension2D -
x + width ≤ maxViewportRange −
1 -
y + height ≤ maxViewportRange −
1 -
0.0≤ minDepth ≤1.0 -
0.0≤ maxDepth ≤1.0 -
minDepth ≤ maxDepth
-
-
Enqueue a render command on this which issues the subsequent steps on the Queue timeline with renderState when executed.
Queue timeline steps:-
Round x, y, width, and height to some uniform precision, no less precise than integer rounding.
-
Set renderState.
[[viewport]]to the extents x, y, width, height, minDepth, and maxDepth.
-
setScissorRect(x, y, width, height)-
Sets the scissor rectangle used during the rasterization stage. After transformation into viewport coordinates any fragments which fall outside the scissor rectangle will be discarded.
Called on:GPURenderPassEncoderthis.Arguments:
Arguments for the GPURenderPassEncoder.setScissorRect(x, y, width, height) method. Parameter Type Nullable Optional Description xGPUIntegerCoordinate✘ ✘ Minimum X value of the scissor rectangle in pixels. yGPUIntegerCoordinate✘ ✘ Minimum Y value of the scissor rectangle in pixels. widthGPUIntegerCoordinate✘ ✘ Width of the scissor rectangle in pixels. heightGPUIntegerCoordinate✘ ✘ Height of the scissor rectangle in pixels. Returns:
undefinedContent timeline steps:
-
Issue the subsequent steps on the Device timeline of this.
[[device]].
Device timeline steps:-
Validate the encoder state of this. If it returns false, return.
-
If any of the following conditions are unsatisfied, invalidate this and return.
-
x+width ≤ this.
[[attachment_size]].width. -
y+height ≤ this.
[[attachment_size]].height.
-
-
Enqueue a render command on this which issues the subsequent steps on the Queue timeline with renderState when executed.
Queue timeline steps:-
Set renderState.
[[scissorRect]]to the extents x, y, width, and height.
-
setBlendConstant(color)-
Sets the constant blend color and alpha values used with
"constant"and"one-minus-constant"GPUBlendFactors.Called on:GPURenderPassEncoderthis.Arguments:
Arguments for the GPURenderPassEncoder.setBlendConstant(color) method. Parameter Type Nullable Optional Description colorGPUColor✘ ✘ The color to use when blending. Returns:
undefinedContent timeline steps:
-
? validate GPUColor shape(color).
-
Issue the subsequent steps on the Device timeline of this.
[[device]].
Device timeline steps:-
Validate the encoder state of this. If it returns false, return.
-
Enqueue a render command on this which issues the subsequent steps on the Queue timeline with renderState when executed.
Queue timeline steps:-
Set renderState.
[[blendConstant]]to color.
-
setStencilReference(reference)-
Sets the
[[stencilReference]]value used during stencil tests with the"replace"GPUStencilOperation.Called on:GPURenderPassEncoderthis.Arguments:
Arguments for the GPURenderPassEncoder.setStencilReference(reference) method. Parameter Type Nullable Optional Description referenceGPUStencilValue✘ ✘ The new stencil reference value. Returns:
undefinedContent timeline steps:
-
Issue the subsequent steps on the Device timeline of this.
[[device]].
Device timeline steps:-
Validate the encoder state of this. If it returns false, return.
-
Enqueue a render command on this which issues the subsequent steps on the Queue timeline with renderState when executed.
Queue timeline steps:-
Set renderState.
[[stencilReference]]to reference.
-
17.2.3. Queries
beginOcclusionQuery(queryIndex)-
Called on:
GPURenderPassEncoderthis.Arguments:
Arguments for the GPURenderPassEncoder.beginOcclusionQuery(queryIndex) method. Parameter Type Nullable Optional Description queryIndexGPUSize32✘ ✘ The index of the query in the query set. Returns:
undefinedContent timeline steps:
-
Issue the subsequent steps on the Device timeline of this.
[[device]].
Device timeline steps:-
Validate the encoder state of this. If it returns false, return.
-
If any of the following conditions are unsatisfied, invalidate this and return.
-
this.
[[occlusion_query_set]]is notnull. -
queryIndex < this.
[[occlusion_query_set]].count. -
The query at same queryIndex must not have been previously written to in this pass.
-
this.
[[occlusion_query_active]]isfalse.
-
-
Set this.
[[occlusion_query_active]]totrue. -
Enqueue a render command on this which issues the subsequent steps on the Queue timeline with renderState when executed.
Queue timeline steps:-
Set renderState.
[[occlusionQueryIndex]]to queryIndex.
-
endOcclusionQuery()-
Called on:
GPURenderPassEncoderthis.Returns:
undefinedContent timeline steps:
-
Issue the subsequent steps on the Device timeline of this.
[[device]].
Device timeline steps:-
Validate the encoder state of this. If it returns false, return.
-
If any of the following conditions are unsatisfied, invalidate this and return.
-
this.
[[occlusion_query_active]]istrue.
-
-
Set this.
[[occlusion_query_active]]tofalse. -
Enqueue a render command on this which issues the subsequent steps on the Queue timeline with renderState when executed.
Queue timeline steps:-
Let passingFragments be non-zero if any fragment samples passed all per-fragment tests since the corresponding
beginOcclusionQuery()command was executed, and zero otherwise.Note: If no draw calls occurred, passingFragments is zero.
-
Write passingFragments into this.
[[occlusion_query_set]]at index renderState.[[occlusionQueryIndex]].
-
17.2.4. Bundles
executeBundles(bundles)-
Executes the commands previously recorded into the given
GPURenderBundles as part of this render pass.When a
GPURenderBundleis executed, it does not inherit the render pass’s pipeline, bind groups, or vertex and index buffers. After aGPURenderBundlehas executed, the render pass’s pipeline, bind group, and vertex/index buffer state is cleared (to the initial, empty values).Note: The state is cleared, not restored to the previous state. This occurs even if zero
GPURenderBundlesare executed.Called on:GPURenderPassEncoderthis.Arguments:
Arguments for the GPURenderPassEncoder.executeBundles(bundles) method. Parameter Type Nullable Optional Description bundlessequence<GPURenderBundle>✘ ✘ List of render bundles to execute. Returns:
undefinedContent timeline steps:
-
Issue the subsequent steps on the Device timeline of this.
[[device]].
Device timeline steps:-
Validate the encoder state of this. If it returns false, return.
-
If any of the following conditions are unsatisfied, invalidate this and return.
-
For each bundle in bundles:
-
bundle must be valid to use with this.
-
this.
[[layout]]must equal bundle.[[layout]]. -
If this.
[[depthReadOnly]]is true, bundle.[[depthReadOnly]]must be true. -
If this.
[[stencilReadOnly]]is true, bundle.[[stencilReadOnly]]must be true.
-
-
-
For each bundle in bundles:
-
Increment this.
[[drawCount]]by bundle.[[drawCount]]. -
Merge bundle.
[[usage scope]]into this.[[usage scope]]. -
Enqueue a render command on this which issues the following steps on the Queue timeline with renderState when executed:
Queue timeline steps:-
Execute each command in bundle.
[[command_list]]with renderState.Note: renderState cannot be changed by executing render bundles. Binding state was already captured at bundle encoding time, and so isn’t used when executing bundles.
-
-
-
Reset the render pass binding state of this.
-
GPURenderPassEncoder
encoder run
the following device
timeline steps:
-
Clear encoder.
[[bind_groups]]. -
Set encoder.
[[pipeline]]tonull. -
Set encoder.
[[index_buffer]]tonull. -
Clear encoder.
[[vertex_buffers]].
18. Bundles
A bundle is a partial, limited pass that is encoded once and can then be executed multiple times as part of future pass encoders without expiring after use like typical command buffers. This can reduce the overhead of encoding and submission of commands which are issued repeatedly without changing.
18.1. GPURenderBundle
[Exposed =(Window ,Worker ),SecureContext ]interface GPURenderBundle { };GPURenderBundle includes GPUObjectBase ;
[[command_list]], of type list<GPU command>-
A list of GPU commands to be submitted to the
GPURenderPassEncoderwhen theGPURenderBundleis executed. [[usage scope]], of type usage scope, initially empty-
The usage scope for this render bundle, stored for later merging into the
GPURenderPassEncoder’s[[usage scope]]inexecuteBundles(). [[layout]], of typeGPURenderPassLayout-
The layout of the render bundle.
[[depthReadOnly]], of typeboolean-
If
true, indicates that the depth component is not modified by executing this render bundle. [[stencilReadOnly]], of typeboolean-
If
true, indicates that the stencil component is not modified by executing this render bundle. [[drawCount]], of typeGPUSize64-
The number of draw commands in this
GPURenderBundle.
18.1.1. Render Bundle Creation
dictionary :GPURenderBundleDescriptor GPUObjectDescriptorBase { };
[Exposed =(Window ,Worker ),SecureContext ]interface {GPURenderBundleEncoder GPURenderBundle finish (optional GPURenderBundleDescriptor descriptor = {}); };GPURenderBundleEncoder includes GPUObjectBase ;GPURenderBundleEncoder includes GPUCommandsMixin ;GPURenderBundleEncoder includes GPUDebugCommandsMixin ;GPURenderBundleEncoder includes GPUBindingCommandsMixin ;GPURenderBundleEncoder includes GPURenderCommandsMixin ;
createRenderBundleEncoder(descriptor)-
Creates a
GPURenderBundleEncoder.Called on:GPUDevicethis.Arguments:
Arguments for the GPUDevice.createRenderBundleEncoder(descriptor) method. Parameter Type Nullable Optional Description descriptorGPURenderBundleEncoderDescriptor✘ ✘ Description of the GPURenderBundleEncoderto create.Returns:
GPURenderBundleEncoderContent timeline steps:
-
? Validate texture format required features of each non-
nullelement of descriptor.colorFormatswith this.[[device]]. -
If descriptor.
depthStencilFormatis provided:-
? Validate texture format required features of descriptor.
depthStencilFormatwith this.[[device]].
-
-
Let e be ! create a new WebGPU object(this,
GPURenderBundleEncoder, descriptor). -
Issue the initialization steps on the Device timeline of this.
-
Return e.
Device timeline initialization steps:-
If any of the following conditions are unsatisfied generate a validation error, invalidate e and return.
-
this must not be lost.
-
descriptor.
colorFormats.size must be ≤ this.[[limits]].maxColorAttachments. -
For each non-
nullcolorFormat in descriptor.colorFormats:-
colorFormat must be a color renderable format.
-
-
Calculating color attachment bytes per sample(descriptor.
colorFormats) must be ≤ this.[[limits]].maxColorAttachmentBytesPerSample. -
If descriptor.
depthStencilFormatis provided:-
descriptor.
depthStencilFormatmust be a depth-or-stencil format.
-
-
There must exist at least one attachment, either:
-
A non-
nullvalue in descriptor.colorFormats, or -
A descriptor.
depthStencilFormat.
-
-
-
Set e.
[[layout]]to a copy of descriptor’s includedGPURenderPassLayoutinterface. -
Set e.
[[depthReadOnly]]to descriptor.depthReadOnly. -
Set e.
[[stencilReadOnly]]to descriptor.stencilReadOnly. -
Set e.
[[drawCount]]to 0.
-
18.1.2. Encoding
dictionary :GPURenderBundleEncoderDescriptor GPURenderPassLayout {boolean depthReadOnly =false ;boolean stencilReadOnly =false ; };
depthReadOnly, of type boolean, defaulting tofalse-
If
true, indicates that the render bundle does not modify the depth component of theGPURenderPassDepthStencilAttachmentof any render pass the render bundle is executed in. stencilReadOnly, of type boolean, defaulting tofalse-
If
true, indicates that the render bundle does not modify the stencil component of theGPURenderPassDepthStencilAttachmentof any render pass the render bundle is executed in.
18.1.3. Finalization
finish(descriptor)-
Completes recording of the render bundle commands sequence.
Called on:GPURenderBundleEncoderthis.Arguments:
Arguments for the GPURenderBundleEncoder.finish(descriptor) method. Parameter Type Nullable Optional Description descriptorGPURenderBundleDescriptor✘ ✔ Returns:
GPURenderBundleContent timeline steps:
-
Let renderBundle be a new
GPURenderBundle. -
Issue the finish steps on the Device timeline of this.
[[device]]. -
Return renderBundle.
Device timeline finish steps:-
Let validationSucceeded be
trueif all of the following requirements are met, andfalseotherwise.-
this must be valid.
-
this.
[[usage scope]]must satisfy usage scope validation. -
this.
[[debug_group_stack]]must be empty.
-
-
If validationSucceeded is
false, then:-
Return an invalidated
GPURenderBundle.
-
Set renderBundle.
[[command_list]]to this.[[commands]]. -
Set renderBundle.
[[usage scope]]to this.[[usage scope]]. -
Set renderBundle.
[[drawCount]]to this.[[drawCount]].
-
19. Queues
19.1. GPUQueueDescriptor
GPUQueueDescriptor
describes a queue request.
dictionary GPUQueueDescriptor :GPUObjectDescriptorBase { };
19.2. GPUQueue
[Exposed =(Window ,Worker ),SecureContext ]interface GPUQueue {undefined submit (sequence <GPUCommandBuffer >commandBuffers );Promise <undefined >onSubmittedWorkDone ();undefined writeBuffer (GPUBuffer buffer ,GPUSize64 bufferOffset ,AllowSharedBufferSource data ,optional GPUSize64 dataOffset = 0,optional GPUSize64 size );undefined writeTexture (GPUTexelCopyTextureInfo destination ,AllowSharedBufferSource data ,GPUTexelCopyBufferLayout dataLayout ,GPUExtent3D size );undefined copyExternalImageToTexture (GPUCopyExternalImageSourceInfo source ,GPUCopyExternalImageDestInfo destination ,GPUExtent3D copySize ); };GPUQueue includes GPUObjectBase ;
GPUQueue has
the following methods:
writeBuffer(buffer, bufferOffset, data, dataOffset, size)-
Issues a write operation of the provided data into a
GPUBuffer.Called on:GPUQueuethis.Arguments:
Arguments for the GPUQueue.writeBuffer(buffer, bufferOffset, data, dataOffset, size) method. Parameter Type Nullable Optional Description bufferGPUBuffer✘ ✘ The buffer to write to. bufferOffsetGPUSize64✘ ✘ Offset in bytes into buffer to begin writing at. dataAllowSharedBufferSource✘ ✘ Data to write into buffer. dataOffsetGPUSize64✘ ✔ Offset in into data to begin writing from. Given in elements if data is a TypedArrayand bytes otherwise.sizeGPUSize64✘ ✔ Size of content to write from data to buffer. Given in elements if data is a TypedArrayand bytes otherwise.Returns:
undefinedContent timeline steps:
-
If data is an
ArrayBufferorDataView, let the element type be "byte". Otherwise, data is a TypedArray; let the element type be the type of the TypedArray. -
Let dataSize be the size of data, in elements.
-
If size is missing, let contentsSize be dataSize − dataOffset. Otherwise, let contentsSize be size.
-
If any of the following conditions are unsatisfied, throw an
OperationErrorand return.-
contentsSize ≥ 0.
-
dataOffset + contentsSize ≤ dataSize.
-
contentsSize, converted to bytes, is a multiple of 4 bytes.
-
-
Let dataContents be a copy of the bytes held by the buffer source data.
-
Let contents be the contentsSize elements of dataContents starting at an offset of dataOffset elements.
-
Issue the subsequent steps on the Device timeline of this.
Device timeline steps:-
If any of the following conditions are unsatisfied, generate a validation error and return.
-
buffer is valid to use with this.
-
buffer.
[[internal state]]is "available". -
bufferOffset, converted to bytes, is a multiple of 4 bytes.
-
bufferOffset + contentsSize, converted to bytes, ≤ buffer.
sizebytes.
-
-
Issue the subsequent steps on the Queue timeline of this.
Queue timeline steps:-
Write contents into buffer starting at bufferOffset.
-
writeTexture(destination, data, dataLayout, size)-
Issues a write operation of the provided data into a
GPUTexture.Called on:GPUQueuethis.Arguments:
Arguments for the GPUQueue.writeTexture(destination, data, dataLayout, size) method. Parameter Type Nullable Optional Description destinationGPUTexelCopyTextureInfo✘ ✘ The texture subresource and origin to write to. dataAllowSharedBufferSource✘ ✘ Data to write into destination. dataLayoutGPUTexelCopyBufferLayout✘ ✘ Layout of the content in data. sizeGPUExtent3D✘ ✘ Extents of the content to write from data to destination. Returns:
undefinedContent timeline steps:
-
? validate GPUOrigin3D shape(destination.
origin). -
? validate GPUExtent3D shape(size).
-
Let dataBytes be a copy of the bytes held by the buffer source data.
Note: This is described as copying all of data to the device timeline, but in practice data could be much larger than necessary. Implementations should optimize by copying only the necessary bytes.
-
Issue the subsequent steps on the Device timeline of this.
Device timeline steps:-
Let aligned be
false. -
Let dataLength be dataBytes.length.
-
If any of the following conditions are unsatisfied, generate a validation error and return.
-
destination.
texture.[[destroyed]]isfalse. -
validating texture buffer copy(destination, dataLayout, dataLength, size,
COPY_DST, aligned) returnstrue.
Note: unlike
GPUCommandEncoder.copyBufferToTexture(), there is no alignment requirement on either dataLayout.bytesPerRowor dataLayout.offset. -
-
Issue the subsequent steps on the Queue timeline of this.
Queue timeline steps:-
Let blockWidth be the texel block width of destination.
texture. -
Let blockHeight be the texel block height of destination.
texture. -
Let dstOrigin be destination.
origin; -
Let dstBlockOriginX be (dstOrigin.x ÷ blockWidth).
-
Let dstBlockOriginY be (dstOrigin.y ÷ blockHeight).
-
Let blockColumns be (copySize.width ÷ blockWidth).
-
Let blockRows be (copySize.height ÷ blockHeight).
-
Assert that dstBlockOriginX, dstBlockOriginY, blockColumns, and blockRows are integers.
-
For each z in the range [0, copySize.depthOrArrayLayers − 1]:
-
Let dstSubregion be texture copy sub-region (z + dstOrigin.z) of destination.
-
For each y in the range [0, blockRows − 1]:
-
For each x in the range [0, blockColumns − 1]:
-
Let blockOffset be the texel block byte offset of dataLayout for (x, y, z) of destination.
texture. -
Set texel block (dstBlockOriginX + x, dstBlockOriginY + y) of dstSubregion to be an equivalent texel representation to the texel block described by dataBytes at offset blockOffset.
-
-
-
-
copyExternalImageToTexture(source, destination, copySize)-
Issues a copy operation of the contents of a platform image/canvas into the destination texture.
This operation performs color encoding into the destination encoding according to the parameters of
GPUCopyExternalImageDestInfo.Copying into a
-srgbtexture results in the same texture bytes, not the same decoded values, as copying into the corresponding non--srgbformat. Thus, after a copy operation, sampling the destination texture has different results depending on whether its format is-srgb, all else unchanged.NOTE:When copying from a"webgl"/"webgl2"context canvas, the WebGL Drawing Buffer may be not exist during certain points in the frame presentation cycle (after the image has been moved to the compositor for display). To avoid this, either:-
Issue
copyExternalImageToTexture()in the same task with WebGL rendering operation, to ensure the copy occurs before the WebGL canvas is presented. -
If not possible, set the
preserveDrawingBufferoption inWebGLContextAttributestotrue, so that the drawing buffer will still contain a copy of the frame contents after they’ve been presented. Note, this extra copy may have a performance cost.
Called on:GPUQueuethis.Arguments:
Arguments for the GPUQueue.copyExternalImageToTexture(source, destination, copySize) method. Parameter Type Nullable Optional Description sourceGPUCopyExternalImageSourceInfo✘ ✘ source image and origin to copy to destination. destinationGPUCopyExternalImageDestInfo✘ ✘ The texture subresource and origin to write to, and its encoding metadata. copySizeGPUExtent3D✘ ✘ Extents of the content to write from source to destination. Returns:
undefinedContent timeline steps:
-
? validate GPUOrigin2D shape(source.
origin). -
? validate GPUOrigin3D shape(destination.
origin). -
? validate GPUExtent3D shape(copySize).
-
Let sourceImage be source.
source -
If sourceImage is not origin-clean, throw a
SecurityErrorand return. -
If any of the following requirements are unmet, throw an
OperationErrorand return.-
source.origin.x + copySize.width must be ≤ the width of sourceImage.
-
source.origin.y + copySize.height must be ≤ the height of sourceImage.
-
copySize.depthOrArrayLayers must be ≤ 1.
-
-
Let usability be ? check the usability of the image argument(source).
-
Issue the subsequent steps on the Device timeline of this.
Device timeline steps:-
Let texture be destination.
texture. -
If any of the following requirements are unmet, generate a validation error and return.
-
usability must be
good. -
texture.
[[destroyed]]must befalse. -
texture must be valid to use with this.
-
validating GPUTexelCopyTextureInfo(destination, copySize) must return
true. -
texture.
usagemust include bothRENDER_ATTACHMENTandCOPY_DST. -
texture.
sampleCountmust be 1. -
texture.
formatmust be one of the following formats (which all supportRENDER_ATTACHMENTusage):
-
-
If copySize.depthOrArrayLayers is > 0, issue the subsequent steps on the Queue timeline of this.
Queue timeline steps:-
Assert that the texel block width of destination.
textureis 1, the texel block height of destination.textureis 1, and that copySize.depthOrArrayLayers is 1. -
Let srcOrigin be source.
origin. -
Let dstOrigin be destination.
origin. -
Let dstSubregion be texture copy sub-region (dstOrigin.z) of destination.
-
For each y in the range [0, copySize.height − 1]:
-
Let srcY be y if source.
flipYisfalseand (copySize.height − 1 − y) otherwise. -
For each x in the range [0, copySize.width − 1]:
-
Set texel block (dstOrigin.x + x, dstOrigin.y + y) of dstSubregion to be an equivalent texel representation of the pixel at (srcOrigin.x + x, srcOrigin.y + srcY) of source.
sourceafter applying any color encoding required by destination.colorSpaceand destination.premultipliedAlpha.
-
-
-
submit(commandBuffers)-
Schedules the execution of the command buffers by the GPU on this queue.
Submitted command buffers cannot be used again.
Called on:GPUQueuethis.Arguments:
Arguments for the GPUQueue.submit(commandBuffers) method. Parameter Type Nullable Optional Description commandBufferssequence<GPUCommandBuffer>✘ ✘ Returns:
undefinedContent timeline steps:
-
Issue the subsequent steps on the Device timeline of this:
Device timeline steps:-
If any of the following requirements are unmet, generate a validation error, invalidate each
GPUCommandBufferin commandBuffers and return.-
Every
GPUCommandBufferin commandBuffers must be valid to use with this. -
Every
GPUCommandBufferin commandBuffers must be unique. -
For each of the following types of resources used by any command in any element of commandBuffers:
GPUBufferb-
b.
[[internal state]]must be "available". GPUTexturet-
t.
[[destroyed]]must befalse. GPUExternalTextureet-
et.
[[expired]]must befalse. GPUQuerySetqs-
qs.
[[destroyed]]must befalse.
Note: For occlusion queries, the
occlusionQuerySetinbeginRenderPass()is not "used" unless it is also used bybeginOcclusionQuery().
-
-
For each commandBuffer in commandBuffers:
-
Invalidate commandBuffer.
-
-
Issue the subsequent steps on the Queue timeline of this:
Queue timeline steps:-
For each commandBuffer in commandBuffers:
-
Execute each command in commandBuffer.
[[command_list]].
-
-
onSubmittedWorkDone()-
Returns a
Promisethat resolves once this queue finishes processing all the work submitted up to this moment.Resolution of this
Promiseimplies the completion ofmapAsync()calls made prior to that call, onGPUBuffers last used exclusively on that queue.Called on:GPUQueuethis.Content timeline steps:
-
Let contentTimeline be the current Content timeline.
-
Let promise be a new promise.
-
Issue the synchronization steps on the Device timeline of this.
-
Return promise.
Device timeline synchronization steps:-
Let event occur upon the completion of all currently-enqueued operations.
-
Listen for timeline event event on this.
[[device]], handled by the subsequent steps on contentTimeline.
Content timeline steps:-
Resolve promise.
-
20. Queries
20.1. GPUQuerySet
[Exposed =(Window ,Worker ),SecureContext ]interface GPUQuerySet {undefined destroy ();readonly attribute GPUQueryType type ;readonly attribute GPUSize32Out count ; };GPUQuerySet includes GPUObjectBase ;
GPUQuerySet
has the following immutable properties:
type, of type GPUQueryType, readonly-
The type of the queries managed by this
GPUQuerySet. count, of type GPUSize32Out, readonly-
The number of queries managed by this
GPUQuerySet.
GPUQuerySet
has the following device timeline properties:
[[destroyed]], of typeboolean, initiallyfalse-
If the query set is destroyed, it can no longer be used in any operation, and its underlying memory can be freed.
20.1.1. QuerySet Creation
A GPUQuerySetDescriptor
specifies the options to use in creating a GPUQuerySet.
dictionary :GPUQuerySetDescriptor GPUObjectDescriptorBase {required GPUQueryType type ;required GPUSize32 count ; };
type, of type GPUQueryType-
The type of queries managed by
GPUQuerySet. count, of type GPUSize32-
The number of queries managed by
GPUQuerySet.
createQuerySet(descriptor)-
Creates a
GPUQuerySet.Called on:GPUDevicethis.Arguments:
Arguments for the GPUDevice.createQuerySet(descriptor) method. Parameter Type Nullable Optional Description descriptorGPUQuerySetDescriptor✘ ✘ Description of the GPUQuerySetto create.Returns:
GPUQuerySetContent timeline steps:
-
If descriptor.
typeis"timestamp", but"timestamp-query"is not enabled for this:-
Throw a
TypeError.
-
-
Let q be ! create a new WebGPU object(this,
GPUQuerySet, descriptor). -
Issue the initialization steps on the Device timeline of this.
-
Return q.
Device timeline initialization steps:-
If any of the following requirements are unmet, generate a validation error, invalidate q and return.
-
Create a device allocation for q where each entry in the query set is zero.
If the allocation fails without side-effects, generate an out-of-memory error, invalidate q, and return.
-
GPUQuerySet
which holds 32 occlusion query results.
const querySet= gpuDevice. createQuerySet({ type: 'occlusion' , count: 32 });
20.1.2. Query Set Destruction
An application that no longer requires a GPUQuerySet
can choose to lose access to it before
garbage collection by calling destroy().
GPUQuerySet
has the following methods:
destroy()-
Destroys the
GPUQuerySet.Called on:GPUQuerySetthis.Returns:
undefinedContent timeline steps:
-
Issue the subsequent steps on the device timeline.
Device timeline steps:-
Set this.
[[destroyed]]totrue.
-
20.2. QueryType
enum {GPUQueryType ,"occlusion" , };"timestamp"
20.3. Occlusion Query
Occlusion query is only available on render passes, to query the number of fragment samples that pass all the per-fragment tests for a set of drawing commands, including scissor, sample mask, alpha to coverage, stencil, and depth tests. Any non-zero result value for the query indicates that at least one sample passed the tests and reached the output merging stage of the render pipeline, 0 indicates that no samples passed the tests.
When beginning a render pass, GPURenderPassDescriptor.occlusionQuerySet
must be set to be able to use occlusion queries during the pass. An occlusion query is begun
and ended by calling beginOcclusionQuery()
and
endOcclusionQuery()
in pairs that cannot be nested, and resolved into a
GPUBuffer
as a 64-bit unsigned integer by GPUCommandEncoder.resolveQuerySet().
20.4. Timestamp Query
Timestamp queries allow applications to write timestamps to a GPUQuerySet,
using:
and then resolve timestamp values (in nanoseconds as a 64-bit unsigned
integer) into
a GPUBuffer,
using GPUCommandEncoder.resolveQuerySet().
Timestamp values are implementation-defined and may not increase monotonically. The physical device may reset the timestamp counter occasionally, which can result in unexpected values such as negative deltas between timestamps that logically should be monotonically increasing. These instances should be rare and can safely be ignored. Applications should not be written in such a way that unexpected timestamps cause an application failure.
Timestamp queries are implemented using high-resolution timers (see § 2.1.7.2 Device/queue-timeline timing). To mitigate security and privacy concerns, their precision must be reduced:
-
Let fineTimestamp be the current timestamp value of the current queue timeline, in nanoseconds, relative to an implementation-defined point in the past.
-
Return the result of calling coarsen time on fineTimestamp with
crossOriginIsolatedCapabilityset tofalse.
Note: Since cross-origin isolation may not apply to
the device timeline
or
queue timeline,
crossOriginIsolatedCapability is never set to true.
Arguments:
-
GPUDevicedevice -
(timestampWritesGPUComputePassTimestampWritesorGPURenderPassTimestampWrites)
Device timeline steps:
-
Return
trueif the following requirements are met, andfalseif not:-
"timestamp-query"must be enabled for device. -
timestampWrites.
querySetmust be valid to use with device. -
timestampWrites.
querySet.typemust be"timestamp". -
Of the write index members in timestampWrites (
beginningOfPassWriteIndex,endOfPassWriteIndex):
-
21. Canvas Rendering
21.1. HTMLCanvasElement.getContext()
A GPUCanvasContext
object is created
via the getContext()
method of an HTMLCanvasElement
instance by passing the string literal 'webgpu' as its contextType argument.
GPUCanvasContext
from an offscreen HTMLCanvasElement:
const canvas= document. createElement( 'canvas' ); const context= canvas. getContext( 'webgpu' );
Unlike WebGL or 2D context creation, the second argument of
HTMLCanvasElement.getContext()
or
OffscreenCanvas.getContext(),
the context creation attribute dictionary options, is ignored.
Instead, use GPUCanvasContext.configure(),
which allows changing the canvas configuration without replacing the canvas.
HTMLCanvasElement
or OffscreenCanvas)
canvas, run the following
content timeline
steps:
-
Let context be a new
GPUCanvasContext. -
Set context.
canvasto canvas. -
Replace the drawing buffer of context.
-
Return context.
Note: User agents should consider issuing
developer-visible warnings when
an ignored options argument is provided when calling getContext()
to get a WebGPU canvas context.
21.2. GPUCanvasContext
[Exposed =(Window ,Worker ),SecureContext ]interface {GPUCanvasContext readonly attribute (HTMLCanvasElement or OffscreenCanvas )canvas ;undefined configure (GPUCanvasConfiguration configuration );undefined unconfigure ();GPUCanvasConfiguration ?getConfiguration ();GPUTexture getCurrentTexture (); };
GPUCanvasContext
has the following content timeline properties:
canvas, of type(HTMLCanvasElement or OffscreenCanvas), readonly-
The canvas this context was created from.
[[configuration]], of typeGPUCanvasConfiguration?, initiallynull-
The options this context is currently configured with.
nullif the context has not been configured or has beenunconfigured. [[textureDescriptor]], of typeGPUTextureDescriptor?, initiallynull-
The currently configured texture descriptor, derived from the
[[configuration]]and canvas.nullif the context has not been configured or has beenunconfigured. [[drawingBuffer]], an image, initially a transparent black image with the same size as the canvas-
The drawing buffer is the working-copy image data of the canvas. It is exposed as writable by
[[currentTexture]](returned bygetCurrentTexture()).The drawing buffer is used to get a copy of the image contents of a context, which occurs when the canvas is displayed or otherwise read. It may be transparent, even if
[[configuration]].alphaModeis"opaque". ThealphaModeonly affects the result of the "get a copy of the image contents of a context" algorithm.The drawing buffer outlives the
[[currentTexture]]and contains the previously-rendered contents even after the canvas has been presented. It is only cleared in Replace the drawing buffer.Any time the drawing buffer is read, implementations must ensure that all previously submitted work (e.g. queue submissions) have completed writing to it via
[[currentTexture]]. [[currentTexture]], of typeGPUTexture?, initiallynull-
The
GPUTextureto draw into for the current frame. It exposes a writable view onto the underlying[[drawingBuffer]].getCurrentTexture()populates this slot ifnull, then returns it.In the steady-state of a visible canvas, any changes to the drawing buffer made through the currentTexture get presented when updating the rendering of a WebGPU canvas. At or before that point, the texture is also destroyed and
[[currentTexture]]is set to tonull, signalling that a new one is to be created by the next call togetCurrentTexture().Destroyingthe currentTexture has no effect on the drawing buffer contents; it only terminates write-access to the drawing buffer early. During the same frame,getCurrentTexture()continues returning the same destroyed texture.Expire the current texture sets the currentTexture to
null. It is called byconfigure(), resizing the canvas, presentation,transferToImageBitmap(), and others. [[lastPresentedImage]], of type(readonly image)?, initiallynull-
The image most recently presented for this canvas in "updating the rendering of a WebGPU canvas". If the device is lost or destroyed, this image may be used as a fallback in "get a copy of the image contents of a context" in order to prevent the canvas from going blank.
Note: This property only needs to exist in implementations which implement the fallback, which is optional.
GPUCanvasContext
has the following methods:
configure(configuration)-
Configures the context for this canvas. This clears the drawing buffer to transparent black (in Replace the drawing buffer).
Called on:GPUCanvasContextthis.Arguments:
Arguments for the GPUCanvasContext.configure(configuration) method. Parameter Type Nullable Optional Description configurationGPUCanvasConfiguration✘ ✘ Desired configuration for the context. Returns: undefined
Content timeline steps:
-
Let device be configuration.
device. -
? Validate texture format required features of configuration.
formatwith device.[[device]]. -
? Validate texture format required features of each element of configuration.
viewFormatswith device.[[device]]. -
If Supported context formats does not contain configuration.
format, throw aTypeError. -
Let descriptor be the GPUTextureDescriptor for the canvas and configuration(this.
canvas, configuration). -
Set this.
[[configuration]]to configuration.NOTE:This spec requires supporting HDR via thetoneMappingoption. If a user agent only supportstoneMapping: "standard", then thetoneMappingmember should not exist inGPUCanvasConfiguration, so it will not exist on the object returned bygetConfiguration()and will not be accessed byconfigure()). This allows websites to detect feature support. -
Set this.
[[textureDescriptor]]to descriptor. -
Replace the drawing buffer of this.
-
Issue the subsequent steps on the Device timeline of device.
Device timeline steps:-
If any of the following requirements are unmet, generate a validation error and return.
-
validating GPUTextureDescriptor(device, descriptor) must return true.
Note: This early validation remains valid until the next
configure()call, except for validation of thesize, which changes when the canvas is resized. -
-
unconfigure()-
Removes the context configuration. Destroys any textures produced while configured.
Called on:GPUCanvasContextthis.Returns: undefined
Content timeline steps:
-
Set this.
[[configuration]]tonull. -
Set this.
[[textureDescriptor]]tonull. -
Replace the drawing buffer of this.
-
getConfiguration()-
Returns the context configuration.
Called on:GPUCanvasContextthis.Returns:
GPUCanvasConfigurationornullContent timeline steps:
-
Let configuration be a copy of this.
[[configuration]]. -
Return configuration.
NOTE:In scenarios wheregetConfiguration()shows thattoneMappingis implemented and the dynamic-range media query indicates HDR support, then WebGPU canvas should render content using the full HDR range instead of clamping values to the SDR range of the HDR display. -
getCurrentTexture()-
Get the
GPUTexturethat will be composited to the document by theGPUCanvasContextnext.NOTE:An application should callgetCurrentTexture()in the same task that renders to the canvas texture. Otherwise, the texture could get destroyed by these steps before the application is finished rendering to it.The expiry task (defined below) is optional to implement. Even if implemented, task source priority is not normatively defined, so may happen as early as the next task, or as late as after all other task sources are empty (see automatic expiry task source). Expiry is only guaranteed when a visible canvas is displayed (updating the rendering of a WebGPU canvas) and in other callers of "Expire the current texture".
Called on:GPUCanvasContextthis.Returns:
GPUTextureContent timeline steps:
-
If this.
[[configuration]]isnull, throw anInvalidStateErrorand return. -
Assert this.
[[textureDescriptor]]is notnull. -
Let device be this.
[[configuration]].device. -
If this.
[[currentTexture]]isnull:-
Replace the drawing buffer of this.
-
Set this.
[[currentTexture]]to the result of calling device.createTexture()with this.[[textureDescriptor]], except with theGPUTexture’s underlying storage pointing to this.[[drawingBuffer]].Note: If the texture can’t be created (e.g. due to validation failure or out-of-memory), this generates and error and returns an invalidated
GPUTexture. Some validation here is redundant with that done inconfigure(). Implementations must not skip this redundant validation.
-
-
Optionally, queue an automatic expiry task with device device and the following steps:
-
Expire the current texture of this.
Note: If this already happened when updating the rendering of a WebGPU canvas, it has no effect.
-
-
Return this.
[[currentTexture]].
Note: The same
GPUTextureobject will be returned by every call togetCurrentTexture()until "Expire the current texture" runs, even if thatGPUTextureis destroyed, failed validation, or failed to allocate. -
Arguments:
-
context: the
GPUCanvasContext
Returns: image contents
Content timeline steps:
-
Let snapshot be a transparent black image of the same size as context.
canvas. -
Let configuration be context.
[[configuration]]. -
If configuration is
null:-
Return snapshot.
Note: The configuration will be
nullif the context has not been configured or has beenunconfigured. This is identical to the behavior when the canvas has no context. -
-
Ensure that all submitted work items (e.g. queue submissions) have completed writing to the image (via context.
[[currentTexture]]). -
If configuration.
deviceis found to be valid:-
Set snapshot to a copy of the context.
[[drawingBuffer]].
Else, if context.
[[lastPresentedImage]]is notnull:-
Optionally, set snapshot to a copy of context.
[[lastPresentedImage]].Note: This is optional because the
[[lastPresentedImage]]may no longer exist, depending on what caused device loss. Implementations may choose to skip it even if do they still have access to that image.
-
-
Let alphaMode be configuration.
alphaMode. -
- If alphaMode is
"opaque": -
-
Clear the alpha channel of snapshot to 1.0.
-
Tag snapshot as being opaque.
Note: If the
[[currentTexture]], if any, has been destroyed (for example in "Expire the current texture"), the alpha channel is unobservable, and implementations may clear the alpha channel in-place. -
- Otherwise:
-
Tag snapshot with alphaMode.
- If alphaMode is
-
Tag snapshot with the
colorSpaceandtoneMappingof configuration. -
Return snapshot.
GPUCanvasContext
context, run
the following content
timeline steps:
-
Expire the current texture of context.
-
Let configuration be context.
[[configuration]]. -
Set context.
[[drawingBuffer]]to a transparent black image of the same size as context.canvas.-
If configuration is null, the drawing buffer is tagged with the color space
"srgb". In this case, the drawing buffer will remain blank until the context is configured. -
If not, the drawing buffer has the specified configuration.
formatand is tagged with the specified configuration.colorSpaceand configuration.toneMapping.
Note: configuration.
alphaModeis ignored until "get a copy of the image contents of a context".NOTE:A newly replaced drawing buffer image behaves as if it is cleared to transparent black, but, like after"discard", an implementation can clear it lazily only if it becomes necessary.Note: This will often be a no-op, if the drawing buffer is already cleared and has the correct configuration.
-
GPUCanvasContext
context, run
the following content
timeline steps:
-
If context.
[[currentTexture]]is notnull:-
Call context.
[[currentTexture]].destroy()(without destroying context.[[drawingBuffer]]) to terminate write access to the image. -
Set context.
[[currentTexture]]tonull.
-
21.3. HTML Specification Hooks
The following algorithms "hook" into algorithms in the HTML specification, and must run at the specified points.
HTMLCanvasElement
or OffscreenCanvas
with a
GPUCanvasContext
context, run the following content timeline steps:
-
Return a copy of the image contents of context.
-
When an
HTMLCanvasElementhas its rendering updated.-
Including when the canvas is the placeholder canvas element of an
OffscreenCanvas.
-
-
When
transferToImageBitmap()creates anImageBitmapfrom the bitmap. (See also transferToImageBitmap from WebGPU.) -
When WebGPU canvas contents are read using other Web APIs, like
drawImage(),texImage2D(),texSubImage2D(),toDataURL(),toBlob(), and so on.
If alphaMode
is "opaque",
this incurs a clear of the alpha channel. Implementations may skip this step when
they are able to read or display images in a way that ignores the alpha channel.
If an application needs a canvas only for interop (not presentation), avoid
"opaque"
if it is not needed.
HTMLCanvasElement
or an OffscreenCanvas
with a placeholder canvas element)
with a GPUCanvasContext
context, which occurs before getting the canvas’s image contents,
in the following sub-steps of the event loop processing model:
-
"update the rendering or user interface of that
Document" -
"update the rendering of that dedicated worker"
Note:
Service and Shared workers do not have "update the rendering" steps
because they cannot render to user-visible canvases.
requestAnimationFrame()
is not exposed in
ServiceWorkerGlobalScope
and SharedWorkerGlobalScope,
and
OffscreenCanvases
from transferControlToOffscreen()
cannot be sent to these workers.
Run the following content timeline steps:
-
Expire the current texture of context.
Note: If this already happened in the task queued by
getCurrentTexture(), it has no effect. -
Set context.
[[lastPresentedImage]]to context.[[drawingBuffer]].Note: This is just a reference, not a copy; the drawing buffer’s contents can’t change in-place after the current texture has expired.
Note:
This does not happen for standalone OffscreenCanvases
(created by new OffscreenCanvas()).
When transferToImageBitmap()
is called on a canvas with
GPUCanvasContext
context, after creating an ImageBitmap
from the canvas’s bitmap,
run the following content timeline steps:
-
Replace the drawing buffer of context.
Note: This makes transferToImageBitmap()
equivalent to "moving" (and possibly alpha-clearing) the image contents into the
ImageBitmap, without a copy.
-
The update the canvas size algorithm.
21.4. GPUCanvasConfiguration
The supported
context formats are the set of GPUTextureFormats:
«"bgra8unorm",
"rgba8unorm",
"rgba16float"».
These formats must be supported when specified as a
GPUCanvasConfiguration.format
regardless of the given
GPUCanvasConfiguration.device.
Note: Canvas configuration cannot use srgb
formats like "bgra8unorm-srgb".
Instead, use the non-srgb equivalent ("bgra8unorm"),
specify the srgb
format in the viewFormats,
and use createView()
to create
a view with an srgb format.
enum GPUCanvasAlphaMode {"opaque" ,"premultiplied" , };enum GPUCanvasToneMappingMode {"standard" ,"extended" , };dictionary {GPUCanvasToneMapping GPUCanvasToneMappingMode = "standard"; };mode dictionary {GPUCanvasConfiguration required GPUDevice device ;required GPUTextureFormat format ;GPUTextureUsageFlags usage = 0x10; // GPUTextureUsage.RENDER_ATTACHMENTsequence <GPUTextureFormat >viewFormats = [];PredefinedColorSpace colorSpace = "srgb";GPUCanvasToneMapping toneMapping = {};GPUCanvasAlphaMode alphaMode = "opaque"; };
GPUCanvasConfiguration
has the following members:
device, of type GPUDevice-
The
GPUDevicethat textures returned bygetCurrentTexture()will be compatible with. format, of type GPUTextureFormat-
The format that textures returned by
getCurrentTexture()will have. Must be one of the Supported context formats. usage, of type GPUTextureUsageFlags, defaulting to0x10-
The usage that textures returned by
getCurrentTexture()will have.RENDER_ATTACHMENTis the default, but is not automatically included if the usage is explicitly set. Be sure to includeRENDER_ATTACHMENTwhen setting a custom usage if you wish to use textures returned bygetCurrentTexture()as color targets for a render pass. viewFormats, of type sequence<GPUTextureFormat>, defaulting to[]-
The formats that views created from textures returned by
getCurrentTexture()may use. colorSpace, of type PredefinedColorSpace, defaulting to"srgb"-
The color space that values written into textures returned by
getCurrentTexture()should be displayed with. toneMapping, of type GPUCanvasToneMapping, defaulting to{}-
The tone mapping determines how the content of textures returned by
getCurrentTexture()are to be displayed.Note: If an implementation doesn’t support HDR WebGPU canvases, it should also not expose this member, to allow for feature detection. See
getConfiguration(). alphaMode, of type GPUCanvasAlphaMode, defaulting to"opaque"-
Determines the effect that alpha values will have on the content of textures returned by
getCurrentTexture()when read, displayed, or used as an image source.
GPUCanvasContext
to be used with a specific GPUDevice,
using the preferred
format for this context:
const canvas= document. createElement( 'canvas' ); const context= canvas. getContext( 'webgpu' ); context. configure({ device: gpuDevice, format: navigator. gpu. getPreferredCanvasFormat(), });
HTMLCanvasElement
or OffscreenCanvas)
canvas,
GPUCanvasConfiguration
configuration)
is a GPUTextureDescriptor
with the following members:
-
size: [canvas.width, canvas.height, 1]. -
viewFormats: configuration.viewFormats.
and other members set to their defaults.
canvas.width refers to HTMLCanvasElement.width
or OffscreenCanvas.width.
canvas.height refers to HTMLCanvasElement.height
or OffscreenCanvas.height.
21.4.1. Canvas Color Space
During presentation, the color values in the canvas are converted to the color space of the screen.
The toneMapping
determines the handling of values
outside of the [0, 1] interval in the color space of the screen.
21.4.2. Canvas Context sizing
All canvas configuration is set in configure()
except for the resolution
of the canvas, which is set by the canvas’s width and height.
Note: Like WebGL and 2d canvas, resizing a WebGPU canvas loses the current contents of the drawing buffer. In WebGPU, it does so by replacing the drawing buffer.
HTMLCanvasElement
or OffscreenCanvas
canvas with a
GPUCanvasContext
context has its width or height attributes set,
update the canvas size by running the following
content timeline
steps:
-
Replace the drawing buffer of context.
-
Let configuration be context.
[[configuration]] -
If configuration is not
null:-
Set context.
[[textureDescriptor]]to the GPUTextureDescriptor for the canvas and configuration(canvas, configuration).
-
Note: This may result in a GPUTextureDescriptor
which exceeds the
maxTextureDimension2D
of the device. In this case,
validation will fail inside getCurrentTexture().
Note: This algorithm is run any time the
canvas width or height attributes are set, even
if their value is not changed.
21.5. GPUCanvasToneMappingMode
This enum specifies how color values are displayed to the screen.
"standard"-
Color values within the standard dynamic range of the screen are unchanged, and all other color values are projected to the standard dynamic range of the screen.
Note: This projection is often accomplished by clamping color values in the color space of the screen to the
[0, 1]interval.For example, suppose that the value(1.035, -0.175, -0.140)is written to an'srgb'canvas.If this is presented to an sRGB screen, then this will be converted to sRGB (which is a no-op, because the canvas is sRGB), then projected into the display’s space. Using component-wise clamping, this results in the sRGB value
(1.0, 0.0, 0.0).If this is presented to a Display P3 screen, then this will be converted to the value
(0.948, 0.106, 0.01)in the Display P3 color space, and no clamping will be needed. "extended"-
Color values in the extended dynamic range of the screen are unchanged, and all other color values are projected to the extended dynamic range of the screen.
Note: This projection is often accomplished by clamping color values in the color space of the screen to the interval of values that the screen is capable of displaying, which may include values greater than
1.For example, suppose that the value(2.5, -0.15, -0.15)is written to an'srgb'canvas.If this is presented to an sRGB screen that is capable of displaying values in the
[0, 4]interval in sRGB space, then this will be converted to sRGB (which is a no-op, because the canvas is sRGB), then projected into the display’s space. If using component-wise clamping, this results in the sRGB value(2.5, 0.0, 0.0).If this is presented to a Display P3 screen that is capable of displaying values in the
[0, 2]interval in Display P3 space, then this will be converted to the value(2.3, 0.545, 0.386)in the Display P3 color space, then projected into the display’s space. If using component-wise clamping, this results in the Display P3 value(2.0, 0.545, 0.386).
21.6. GPUCanvasAlphaMode
This enum selects how the contents of the canvas will be interpreted when read, when displayed to the screen or used as an image source (in drawImage, toDataURL, etc.)
Below, src is a value in the canvas texture, and dst is an image that the canvas
is being composited into (e.g. an HTML page rendering, or a 2D canvas).
"opaque"-
Read RGB as opaque and ignore alpha values. If the content is not already opaque, the alpha channel is cleared to 1.0 in "get a copy of the image contents of a context".
"premultiplied"-
Read RGBA as premultiplied: color values are premultiplied by their alpha value. 100% red at 50% alpha is
[0.5, 0, 0, 0.5].If the canvas texture contains out-of-gamut premultiplied RGBA values at the time the canvas contents are read, the behavior depends on whether the canvas is:
- used as an image source
-
Values are preserved, as described in color space conversion.
- displayed to the screen
-
Compositing results are undefined.
Note: This is true even if color space conversion would produce in-gamut values before compositing, because the intermediate format for compositing is not specified.
22. Errors & Debugging
During the normal course of operation of WebGPU, errors are raised via dispatch error.
After a device is lost, errors are no longer surfaced, where possible. After this point, implementations do not need to run validation or error tracking:
-
The validity of objects on the device becomes unobservable.
-
popErrorScope()anduncapturederrorstop reporting errors. (No errors are generated by the device loss itself. Instead, theGPUDevice.lostpromise resolves to indicate the device is lost.) -
All operations which send a message back to the content timeline will skip their usual steps. Most will appear to succeed, except for
mapAsync(), which produces an error because it is impossible to provide the correct mapped data after the device has been lost.This makes it unobservable whether other types of operations (that don’t send messages back) actually execute or not.
22.1. Fatal Errors
enum {GPUDeviceLostReason ,"unknown" , }; ["destroyed" Exposed =(Window ,Worker ),SecureContext ]interface {GPUDeviceLostInfo readonly attribute GPUDeviceLostReason ;reason readonly attribute DOMString ; };message partial interface GPUDevice {readonly attribute Promise <GPUDeviceLostInfo >lost ; };
GPUDevice has
the following additional attributes:
lost, of type Promise<GPUDeviceLostInfo>, readonly-
A slot-backed attribute holding a promise which is created with the device, remains pending for the lifetime of the device, then resolves when the device is lost.
Upon initialization, it is set to a new promise.
22.2. GPUError
[Exposed =(Window ,Worker ),SecureContext ]interface GPUError {readonly attribute DOMString message ; };
GPUError is the
base interface for all errors surfaced from popErrorScope()
and the uncapturederror
event.
Errors must only be generated for operations that explicitly state the conditions one may be generated under in their respective algorithms, and the subtype of error that is generated.
No errors are generated from a device which is lost. See § 22 Errors & Debugging.
Note: GPUError may gain
new subtypes in future versions of this spec. Applications should handle
this possibility, using only the error’s message
when possible, and specializing using
instanceof. Use error.constructor.name when it’s necessary to serialize an error
(e.g. into
JSON, for a debug report).
GPUError has the
following immutable
properties:
message, of type DOMString, readonly-
A human-readable, localizable text message providing information about the error that occurred.
Note: This message is generally intended for application developers to debug their applications and capture information for debug reports, not to be surfaced to end-users.
Note: User agents should not include potentially machine-parsable details in this message, such as free system memory on
"out-of-memory"or other details about the conditions under which memory was exhausted.Note: The
messageshould follow the best practices for language and direction information. This includes making use of any future standards which may emerge regarding the reporting of string language and direction metadata.Editorial note: At the time of this writing, no language/direction recommendation is available that provides compatibility and consistency with legacy APIs, but when there is, adopt it formally.
[Exposed =(Window ,Worker ),SecureContext ]interface :GPUValidationError GPUError {(constructor DOMString ); };message
GPUValidationError
is a subtype of GPUError which
indicates that an operation did not
satisfy all validation requirements. Validation errors are always indicative of an application
error, and is expected to fail the same way across all devices assuming the same
[[features]]
and [[limits]]
are in use.
GPUDevice
device, run the following steps:
Device timeline steps:
-
Let error be a new
GPUValidationErrorwith an appropriate error message. -
Dispatch error error to device.
[Exposed =(Window ,Worker ),SecureContext ]interface :GPUOutOfMemoryError GPUError {(constructor DOMString ); };message
GPUOutOfMemoryError
is a subtype of GPUError which
indicates that there was not enough free
memory to complete the requested operation. The operation may succeed if attempted again with a
lower memory requirement (like using smaller texture dimensions), or if memory used by other
resources is released first.
GPUDevice
device, run the following steps:
Device timeline steps:
-
Let error be a new
GPUOutOfMemoryErrorwith an appropriate error message. -
Dispatch error error to device.
[Exposed =(Window ,Worker ),SecureContext ]interface :GPUInternalError GPUError {(constructor DOMString ); };message
GPUInternalError
is a subtype of GPUError which
indicates than an operation failed for a
system or implementation-specific reason even when all validation requirements have been satisfied.
For example, the operation may exceed the capabilities of the implementation in a way not easily
captured by the supported
limits. The same operation may succeed on other devices or under
difference circumstances.
GPUDevice
device, run the following steps:
Device timeline steps:
-
Let error be a new
GPUInternalErrorwith an appropriate error message. -
Dispatch error error to device.
22.3. Error Scopes
A GPU error scope
captures GPUErrors that
were generated while the
GPU error scope was
current. Error scopes are used to isolate errors that occur within a set
of WebGPU calls, typically for debugging purposes or to make an operation more fault tolerant.
GPU error scope has the following device timeline properties:
[[errors]], of type list<GPUError>, initially []-
The
GPUErrors, if any, observed while the GPU error scope was current. [[filter]], of typeGPUErrorFilter-
Determines what type of
GPUErrorthis GPU error scope observes.
enum {GPUErrorFilter "validation" ,"out-of-memory" ,"internal" , };partial interface GPUDevice {undefined pushErrorScope (GPUErrorFilter filter );Promise <GPUError ?>popErrorScope (); };
GPUErrorFilter
defines the type of errors that should be caught when calling
pushErrorScope():
"validation"-
Indicates that the error scope will catch a
GPUValidationError. "out-of-memory"-
Indicates that the error scope will catch a
GPUOutOfMemoryError. "internal"-
Indicates that the error scope will catch a
GPUInternalError.
GPUDevice has
the following device timeline properties:
[[errorScopeStack]], of type stack<GPU error scope>-
A stack of GPU error scopes that have been pushed to the
GPUDevice.
GPUError
error and GPUDevice
device is determined by issuing the following steps to the device timeline of device:
Device timeline steps:
-
If error is an instance of:
GPUValidationError-
Let type be "validation".
GPUOutOfMemoryError-
Let type be "out-of-memory".
GPUInternalError-
Let type be "internal".
-
Let scope be the last item of device.
[[errorScopeStack]]. -
While scope is not
undefined:-
If scope.
[[filter]]is type, return scope. -
Set scope to the previous item of device.
[[errorScopeStack]].
-
-
Return
undefined.
GPUError
error on GPUDevice
device, run the following device timeline steps:
Note: No errors are generated from a device which is lost. If this algorithm is called while device is lost, it will not be observable to the application. See § 22 Errors & Debugging.
-
Let scope be the current error scope for error and device.
-
If scope is not
undefined:-
Append error to scope.
[[errors]]. -
Return.
-
-
Otherwise issue the following steps to the content timeline:
-
If the user agent chooses, queue a global task for GPUDevice device with the following steps:
-
Fire a
GPUUncapturedErrorEventnamed "uncapturederror" on device, with anerrorof error.
-
Note: After dispatching the event, user agents
should surface uncaptured errors to
developers, for example as warnings in the browser’s developer console, unless the event’s
defaultPrevented
is true. In other words, calling preventDefault()
on the event should silence the console warning.
Note: The user agent may choose to throttle or limit
the number of GPUUncapturedErrorEvents
that a GPUDevice
can raise to prevent an excessive amount of error handling or logging from
impacting performance.
pushErrorScope(filter)-
Pushes a new GPU error scope onto the
[[errorScopeStack]]for this.Called on:GPUDevicethis.Arguments:
Arguments for the GPUDevice.pushErrorScope(filter) method. Parameter Type Nullable Optional Description filterGPUErrorFilter✘ ✘ Which class of errors this error scope observes. Returns:
undefinedContent timeline steps:
-
Issue the subsequent steps on the Device timeline of this.
Device timeline steps:-
Let scope be a new GPU error scope.
-
Set scope.
[[filter]]to filter. -
Push scope onto this.
[[errorScopeStack]].
-
popErrorScope()-
Pops a GPU error scope off the
[[errorScopeStack]]for this and resolves to anyGPUErrorobserved by the error scope, ornullif none.There is no guarantee of the ordering of promise resolution.
Called on:GPUDevicethis.Content timeline steps:
-
Let contentTimeline be the current Content timeline.
-
Let promise be a new promise.
-
Issue the check steps on the Device timeline of this.
-
Return promise.
Device timeline check steps:-
If this is lost:
-
Issue the following steps on contentTimeline:
Content timeline steps:-
Resolve promise with
null.
-
-
Return.
Note: No errors are generated from a device which is lost. See § 22 Errors & Debugging.
-
-
If any of the following requirements are unmet:
-
this.
[[errorScopeStack]].size must be > 0.
Then issue the following steps on contentTimeline and return:
Content timeline steps:-
Reject promise with an
OperationError.
-
-
Let scope be the result of popping an item off of this.
[[errorScopeStack]]. -
Let error be any one of the items in scope.
[[errors]], ornullif there are none.For any two errors E1 and E2 in the list, if E2 was caused by E1, E2 should not be the one selected.
Note: For example, if E1 comes from
t=createTexture(), and E2 comes fromt.createView()becausetwas invalid, E1 should be be preferred since it will be easier for a developer to understand what went wrong. Since both of these areGPUValidationErrors, the only difference will be in themessagefield, which is meant only to be read by humans anyway. -
At an unspecified point now or in the future, issue the subsequent steps on contentTimeline.
Note: By allowing
popErrorScope()calls to resolve in any order, with any of the errors observed by the scope, this spec allows validation to complete out of order, as long as any state observations are made at the appropriate point in adherence to this spec. For example, this allows implementations to perform shader compilation, which depends only on non-stateful inputs, to be completed on a background thread in parallel with other device-timeline work, and report any resulting errors later.
Content timeline steps:-
Resolve promise with error.
-
GPUDevice
operation that may fail:
gpuDevice. pushErrorScope( 'validation' ); let sampler= gpuDevice. createSampler({ maxAnisotropy: 0 , // Invalid, maxAnisotropy must be at least 1. }); gpuDevice. popErrorScope(). then(( error) => { if ( error) { // There was an error creating the sampler, so discard it. sampler= null ; console. error( `An error occured while creating sampler: ${ error. message} ` ); } });
For example: An error scope that only contains the creation of a single resource, such as a texture or buffer, can be used to detect failures such as out of memory conditions, in which case the application may try freeing some resources and trying the allocation again.
Error scopes do not identify which command failed, however. So, for instance, wrapping all the commands executed while loading a model in a single error scope will not offer enough granularity to determine if the issue was due to memory constraints. As a result freeing resources would usually not be a productive response to a failure of that scope. A more appropriate response would be to allow the application to fall back to a different model or produce a warning that the model could not be loaded. If responding to memory constraints is desired, the operations allocating memory can always be wrapped in a smaller nested error scope.
22.4. Telemetry
When a GPUError
is generated that is not observed by any GPU error scope, the user agent may fire an event named uncapturederror at a GPUDevice
using GPUUncapturedErrorEvent.
Note: uncapturederror
events are intended to be used for telemetry and reporting
unexpected errors. They may not be dispatched for all uncaptured errors (for example, there may be a limit
on the number of errors surfaced), and should not be used for handling known error cases that may occur
during
normal operation of an application. Prefer using pushErrorScope()
and
popErrorScope()
in those cases.
[Exposed =(Window ,Worker ),SecureContext ]interface :GPUUncapturedErrorEvent Event {(constructor DOMString ,type GPUUncapturedErrorEventInit ); [gpuUncapturedErrorEventInitDict SameObject ]readonly attribute GPUError error ; };dictionary :GPUUncapturedErrorEventInit EventInit {required GPUError ; };error
GPUUncapturedErrorEvent
has the following attributes:
error, of type GPUError, readonly-
A slot-backed attribute holding an object representing the error that was uncaptured. This has the same type as errors returned by
popErrorScope().
partial interface GPUDevice {attribute EventHandler onuncapturederror ; };
GPUDevice has
the following content timeline properties:
onuncapturederror, of type EventHandler-
An event handler IDL attribute for the
uncapturederrorevent type.
GPUDevice:
gpuDevice. addEventListener( 'uncapturederror' , ( event) => { // Re-surface the error, because adding an event listener may silence console logs. console. error( 'A WebGPU error was not captured:' , event. error); myEngineDebugReport. uncapturedErrors. push({ type: event. error. constructor . name, message: event. error. message, }); });
23. Detailed Operations
This section describes the details of various GPU operations.
23.1. Computing
Computing operations provide direct access to GPU’s programmable hardware.
Compute shaders do not have shader stage inputs or outputs; their results are
side effects from writing data into storage bindings bound either as
GPUBufferBindingLayout
with GPUBufferBindingType
"storage"
or as GPUStorageTextureBindingLayout.
These operations are encoded within GPUComputePassEncoder
as:
The main compute algorithm:
Arguments:
-
descriptor: Description of the current
GPUComputePipeline. -
dispatchCall: The dispatch call parameters. May come from function arguments or an
INDIRECTbuffer.
-
Let computeStage be descriptor.
compute. -
Let workgroupSize be the computed workgroup size for computeStage.
entryPointafter applying computeStage.constantsto computeStage.module. -
For workgroupX in range
[0, dispatchCall.:workgroupCountX]-
For workgroupY in range
[0, dispatchCall.:workgroupCountY]-
For workgroupZ in range
[0, dispatchCall.:workgroupCountZ]-
For localX in range
[0, workgroupSize.:x]-
For localY in range
[0, workgroupSize.:y]-
For localZ in range
[0, workgroupSize.:y]-
Let invocation be
{ computeStage, workgroupX, workgroupY, workgroupZ, localX, localY, localZ } -
Append invocation to computeInvocations.
-
-
-
-
-
-
-
For every invocation in computeInvocations, in any order the device chooses, including in parallel:
-
Set the shader builtins:
-
Set the num_workgroups builtin, if any, to
(
dispatchCall.workgroupCountX,
dispatchCall.workgroupCountY,
dispatchCall.workgroupCountZ
) -
Set the workgroup_id builtin, if any, to
(
invocation.workgroupX,
invocation.workgroupY,
invocation.workgroupZ
) -
Set the local_invocation_id builtin, if any, to
(
invocation.localX,
invocation.localY,
invocation.localZ
) -
Set the global_invocation_id builtin, if any, to
(.
invocation.workgroupX * workgroupSize.x+ invocation.localX,
invocation.workgroupY * workgroupSize.y+ invocation.localY,
invocation.workgroupZ * workgroupSize.z+ invocation.localZ
) -
Set the local_invocation_index builtin, if any, to
invocation.localX + (invocation.localY * workgroupSize.x) + (invocation.localZ * workgroupSize.x* workgroupSize.y)
-
-
Invoke the compute shader entry point described by invocation.computeStage.
-
Note: Shader invocations have no guaranteed order, and will generally run in parallel according to device capabilities. Developers should not assume that any given invocation or workgroup will complete before any other one is started. Some devices may appear to execute in a consistent order, but this behavior should not be relied on as it will not perform identically across all devices. Shaders that require synchronization across invocations must use Synchronization Built-in Functions to coordinate execution.
The device may become lost if shader execution does not end in a reasonable amount of time, as determined by the user agent.
23.2. Rendering
Rendering is done by a set of GPU operations that are executed within GPURenderPassEncoder,
and result in modifications of the texture data, viewed by the render pass attachments.
These operations are encoded with:
Note: rendering is the traditional use of GPUs, and is supported by multiple fixed-function blocks in hardware.
The main rendering algorithm:
Arguments:
-
pipeline: The current
GPURenderPipeline. -
drawCall: The draw call parameters. May come from function arguments or an
INDIRECTbuffer. -
state: RenderState of the
GPURenderCommandsMixinwhere the draw call is issued.
-
Let descriptor be pipeline.
[[descriptor]]. -
Resolve indices. See § 23.2.1 Index Resolution.
Let vertexList be the result of resolve indices(drawCall, state).
-
Process vertices. See § 23.2.2 Vertex Processing.
Execute process vertices(vertexList, drawCall, descriptor.
vertex, state). -
Assemble primitives. See § 23.2.3 Primitive Assembly.
Execute assemble primitives(vertexList, drawCall, descriptor.
primitive). -
Clip primitives. See § 23.2.4 Primitive Clipping.
Let primitiveList be the result of this stage.
-
Rasterize. See § 23.2.5 Rasterization.
Let rasterizationList be the result of rasterize(primitiveList, state).
-
Process fragments. See § 23.2.6 Fragment Processing.
Gather a list of fragments, resulting from executing process fragment(rasterPoint, descriptor, state) for each rasterPoint in rasterizationList.
-
Write pixels. See § 23.2.7 Output Merging.
For each non-null fragment of fragments:
-
Execute process depth stencil(fragment, pipeline, state).
-
Execute process color attachments(fragment, pipeline, state).
-
23.2.1. Index Resolution
At the first stage of rendering, the pipeline builds a list of vertices to process for each instance.
Arguments:
-
drawCall: The draw call parameters. May come from function arguments or an
INDIRECTbuffer. -
state: The snapshot of the
GPURenderCommandsMixinstate at the time of the draw call.
Returns: list of integer indices.
-
Let vertexIndexList be an empty list of indices.
-
If drawCall is an indexed draw call:
-
Initialize the vertexIndexList with drawCall.indexCount integers.
-
For i in range 0 .. drawCall.indexCount (non-inclusive):
-
Let relativeVertexIndex be fetch index(i + drawCall.
firstIndex, state.[[index_buffer]]). -
If relativeVertexIndex has the special value
"out of bounds", return the empty list.Note: Implementations may choose to display a warning when this occurs, especially when it is easy to detect (like in non-indirect indexed draw calls).
-
Append drawCall.
baseVertex+ relativeVertexIndex to the vertexIndexList.
-
-
-
Otherwise:
-
Initialize the vertexIndexList with drawCall.vertexCount integers.
-
Set each vertexIndexList item i to the value drawCall.firstVertex + i.
-
-
Return vertexIndexList.
Note: in the case of indirect draw calls, the
indexCount, vertexCount,
and other properties of drawCall are read from the indirect buffer
instead of the draw command itself.
Arguments:
-
i: Index of a vertex index to fetch.
-
state: The snapshot of the
GPURenderCommandsMixinstate at the time of the draw call.
Returns: unsigned integer or "out of bounds"
-
Let indexSize be defined by the state.
[[index_format]]: -
If state.
[[index_buffer_offset]]+ |i + 1| × indexSize > state.[[index_buffer_size]], return the special value"out of bounds". -
Interpret the data in state.
[[index_buffer]], starting at offset state.[[index_buffer_offset]]+ i × indexSize, of size indexSize bytes, as an unsigned integer and return it.
23.2.2. Vertex Processing
Vertex processing stage is a programmable stage of the render pipeline that processes the vertex attribute data, and produces clip space positions for § 23.2.4 Primitive Clipping, as well as other data for the § 23.2.6 Fragment Processing.
Arguments:
-
vertexIndexList: List of vertex indices to process (mutable, passed by reference).
-
drawCall: The draw call parameters. May come from function arguments or an
INDIRECTbuffer. -
desc: The descriptor of type
GPUVertexState. -
state: The snapshot of the
GPURenderCommandsMixinstate at the time of the draw call.
Each vertex vertexIndex in the vertexIndexList,
in each instance of index rawInstanceIndex, is processed independently.
The rawInstanceIndex is in range from 0 to drawCall.instanceCount - 1, inclusive.
This processing happens in parallel, and any side effects, such as
writes into GPUBufferBindingType
"storage"
bindings,
may happen in any order.
-
Let instanceIndex be rawInstanceIndex + drawCall.firstInstance.
-
For each non-
nullvertexBufferLayout in the list of desc.buffers:-
Let i be the index of the buffer layout in this list.
-
Let vertexBuffer, vertexBufferOffset, and vertexBufferBindingSize be the buffer, offset, and size at slot i of state.
[[vertex_buffers]]. -
Let vertexElementIndex be dependent on vertexBufferLayout.
stepMode:"vertex"-
vertexIndex
"instance"-
instanceIndex
-
Let drawCallOutOfBounds be
false. -
For each attributeDesc in vertexBufferLayout.
attributes:-
Let attributeOffset be vertexBufferOffset + vertexElementIndex * vertexBufferLayout.
arrayStride+ attributeDesc.offset. -
If attributeOffset + byteSize(attributeDesc.
format) > vertexBufferOffset + vertexBufferBindingSize:-
Set drawCallOutOfBounds to
true. -
Optionally (implementation-defined), empty vertexIndexList and return, cancelling the draw call.
Note: This allows implementations to detect out-of-bounds values in the index buffer before issuing a draw call, instead of using invalid memory reference behavior.
-
-
-
For each attributeDesc in vertexBufferLayout.
attributes:-
If drawCallOutOfBounds is
true:-
Load the attribute data according to WGSL’s invalid memory reference behavior, from vertexBuffer.
Note: Invalid memory reference allows several behaviors, including actually loading the "correct" result for an attribute that is in-bounds, even when the draw-call-wide drawCallOutOfBounds is
true.
Otherwise:
-
Let attributeOffset be vertexBufferOffset + vertexElementIndex * vertexBufferLayout.
arrayStride+ attributeDesc.offset. -
Load the attribute data of format attributeDesc.
formatfrom vertexBuffer starting at offset attributeOffset. The components are loaded in the orderx,y,z,wfrom buffer memory.
-
-
Convert the data into a shader-visible format, according to channel formats rules.
An attribute of type"snorm8x2"and byte values of[0x70, 0xD0]will be converted tovec2<f32>(0.88, -0.38)in WGSL. -
Adjust the data size to the shader type:
-
if both are scalar, or both are vectors of the same dimensionality, no adjustment is needed.
-
if data is vector but the shader type is scalar, then only the first component is extracted.
-
if both are vectors, and data has a higher dimension, the extra components are dropped.
An attribute of type"float32x3"and valuevec3<f32>(1.0, 2.0, 3.0)will exposed to the shader asvec2<f32>(1.0, 2.0)if a 2-component vector is expected. -
if the shader type is a vector of higher dimensionality, or the data is a scalar, then the missing components are filled from
vec4<*>(0, 0, 0, 1)value.An attribute of type"sint32"and value5will be exposed to the shader asvec4<i32>(5, 0, 0, 1)if a 4-component vector is expected.
-
-
Bind the data to vertex shader input location attributeDesc.
shaderLocation.
-
-
-
For each
GPUBindGroupgroup at index in state.[[bind_groups]]:-
For each resource
GPUBindingResourcein the bind group:-
Let entry be the corresponding
GPUBindGroupLayoutEntryfor this resource. -
If entry.
visibilityincludesVERTEX:-
Bind the resource to the shader under group index and binding
GPUBindGroupLayoutEntry.binding.
-
-
-
-
Set the shader builtins:
-
Set the
vertex_indexbuiltin, if any, to vertexIndex. -
Set the
instance_indexbuiltin, if any, to instanceIndex.
-
-
Invoke the vertex shader entry point described by desc.
Note: The target platform caches the results of vertex shader invocations. There is no guarantee that any vertexIndex that repeats more than once will result in multiple invocations. Similarly, there is no guarantee that a single vertexIndex will only be processed once.
The device may become lost if shader execution does not end in a reasonable amount of time, as determined by the user agent.
23.2.3. Primitive Assembly
Primitives are assembled by a fixed-function stage of GPUs.
Arguments:
-
vertexIndexList: List of vertex indices to process.
-
drawCall: The draw call parameters. May come from function arguments or an
INDIRECTbuffer. -
desc: The descriptor of type
GPUPrimitiveState.
For each instance, the primitives get assembled from the vertices that have been processed by the shaders, based on the vertexIndexList.
-
First, if the primitive topology is a strip, (which means that desc.
stripIndexFormatis not undefined) and the drawCall is indexed, the vertexIndexList is split into sub-lists using the maximum value of desc.stripIndexFormatas a separator.Example: a vertexIndexList with values
[1, 2, 65535, 4, 5, 6]of type"uint16"will be split in sub-lists[1, 2]and[4, 5, 6]. -
For each of the sub-lists vl, primitive generation is done according to the desc.
topology:"line-list"-
Line primitives are composed from (vl.0, vl.1), then (vl.2, vl.3), then (vl.4 to vl.5), etc. Each subsequent primitive takes 2 vertices.
"line-strip"-
Line primitives are composed from (vl.0, vl.1), then (vl.1, vl.2), then (vl.2, vl.3), etc. Each subsequent primitive takes 1 vertex.
"triangle-list"-
Triangle primitives are composed from (vl.0, vl.1, vl.2), then (vl.3, vl.4, vl.5), then (vl.6, vl.7, vl.8), etc. Each subsequent primitive takes 3 vertices.
"triangle-strip"-
Triangle primitives are composed from (vl.0, vl.1, vl.2), then (vl.2, vl.1, vl.3), then (vl.2, vl.3, vl.4), then (vl.4, vl.3, vl.5), etc. Each subsequent primitive takes 1 vertices.
Any incomplete primitives are dropped.
23.2.4. Primitive Clipping
Vertex shaders have to produce a built-in position (of type vec4<f32>),
which denotes the clip
position of a vertex in clip space coordinates.
Primitives are clipped to the clip volume, which, for any clip position p inside a primitive, is defined by the following inequalities:
-
−p.w ≤ p.x ≤ p.w
-
−p.w ≤ p.y ≤ p.w
-
0 ≤ p.z ≤ p.w (depth clipping)
When the "clip-distances"
feature is enabled, this clip
volume can
be further restricted by user-defined half-spaces by declaring clip_distances in the
output of vertex stage. Each value in the clip_distances array will be linearly
interpolated across the primitive, and the portion of the primitive with interpolated distances less
than 0 will be clipped.
If descriptor.primitive.unclippedDepth
is true,
depth clipping is not
applied: the clip volume is not
bounded in the z dimension.
A primitive passes through this stage unchanged if every one of its edges
lie entirely inside the clip
volume.
If the edges of a primitives intersect the boundary of the clip volume,
the intersecting edges are reconnected by new edges that lie along the boundary of the clip volume.
For triangular primitives (descriptor.primitive.topology
is
"triangle-list"
or "triangle-strip"),
this reconnection
may result in introduction of new vertices into the polygon, internally.
If a primitive intersects an edge of the clip volume’s boundary, the clipped polygon must include a point on this boundary edge.
If the vertex shader outputs other floating-point values (scalars and vectors), qualified with "perspective" interpolation, they also get clipped. The output values associated with a vertex that lies within the clip volume are unaffected by clipping. If a primitive is clipped, however, the output values assigned to vertices produced by clipping are clipped.
Considering an edge between vertices a and b that got clipped, resulting in the vertex c, let’s define t to be the ratio between the edge vertices: c.p = t × a.p + (1 − t) × b.p, where x.p is the output clip position of a vertex x.
For each vertex output value "v" with a corresponding fragment input, a.v and b.v would be the outputs for a and b vertices respectively. The clipped shader output c.v is produced based on the interpolation qualifier:
- flat
-
Flat interpolation is unaffected, and is based on the provoking vertex, which is determined by the interpolation sampling mode declared in the shader. The output value is the same for the whole primitive, and matches the vertex output of the provoking vertex.
- linear
-
The interpolation ratio gets adjusted against the perspective coordinates of the clip positions, so that the result of interpolation is linear in screen space.
- perspective
-
The value is linearly interpolated in clip space, producing perspective-correct values.
The result of primitive clipping is a new set of primitives, which are contained within the clip volume.
23.2.5. Rasterization
Rasterization is the hardware processing stage that maps the generated primitives
to the 2-dimensional rendering area of the framebuffer -
the set of render attachments in the current GPURenderPassEncoder.
This rendering area is split into an even grid of pixels.
The framebuffer coordinates start from the top-left corner of the render targets. Each unit corresponds exactly to one pixel. See § 3.3 Coordinate Systems for more information.
Rasterization determines the set of pixels affected by a primitive. In case of multi-sampling,
each pixel is further split into
descriptor.multisample.count
samples.
The standard sample
patterns are as follows,
with positions in framebuffer coordinates relative to the top-left corner of the pixel,
such that the pixel ranges from (0, 0) to (1, 1):
multisample.count
| Sample positions |
|---|---|
| 1 | Sample 0: (0.5, 0.5) |
| 4 |
Sample 0: (0.375, 0.125) Sample 1: (0.875, 0.375) Sample 2: (0.125, 0.625) Sample 3: (0.625, 0.875) |
Implementations must use the standard sample pattern for the given
multisample.count
when performing rasterization.
Let’s define a FragmentDestination to contain:
- position
-
the 2D pixel position using framebuffer coordinates
- sampleIndex
-
an integer in case § 23.2.10 Per-Sample Shading is active, or
nullotherwise
We’ll also use a notion of normalized device coordinates, or NDC. In this coordinate system, the viewport bounds range in X and Y from -1 to 1, and in Z from 0 to 1.
Rasterization produces a list of RasterizationPoints, each containing the following data:
- destination
-
refers to FragmentDestination
- coverageMask
-
refers to multisample coverage mask (see § 23.2.11 Sample Masking)
- frontFacing
-
is true if it’s a point on the front face of a primitive
- perspectiveDivisor
-
refers to interpolated 1.0 ÷ W across the primitive
- depth
-
refers to the depth in viewport coordinates, i.e. between the
[[viewport]]minDepthandmaxDepth. - primitiveVertices
-
refers to the list of vertex outputs forming the primitive
- barycentricCoordinates
-
refers to § 23.2.5.3 Barycentric coordinates
Arguments:
-
primitiveList: List of primitives to rasterize.
-
state: The active RenderState.
Returns: list of RasterizationPoint.
Each primitive in primitiveList is processed independently. However, the order of primitives affects later stages, such as depth/stencil operations and pixel writes.
-
First, the clipped vertices are transformed into NDC - normalized device coordinates. Given the output position p, the NDC position and perspective divisor are:
ndc(p) = vector(p.x ÷ p.w, p.y ÷ p.w, p.z ÷ p.w)
divisor(p) = 1.0 ÷ p.w
-
Let vp be state.
[[viewport]]. Map the NDC position n into viewport coordinates:-
Compute framebuffer coordinates from the render target offset and size:
framebufferCoords(n) = vector(vp.
x+ 0.5 × (n.x + 1) × vp.width, vp.y+ 0.5 × (−n.y + 1) × vp.height) -
Compute depth by linearly mapping [0,1] to the viewport depth range:
depth(n) = vp.
minDepth+ n.z× ( vp.maxDepth- vp.minDepth)
-
-
Let rasterizationPoints be the list of points, each having its attributes (
divisor(p),framebufferCoords(n),depth(n), etc.) interpolated according to its position on the primitive, using the same interpolation as § 23.2.4 Primitive Clipping. If the attribute is user-defined (not a built-in output value) then the interpolation type specified by the @interpolate WGSL attribute is used. -
Proceed with a specific rasterization algorithm, depending on
primitive.topology:"point-list"-
The point, if not filtered by § 23.2.4 Primitive Clipping, goes into § 23.2.5.1 Point Rasterization.
"line-list"or"line-strip"-
The line cut by § 23.2.4 Primitive Clipping goes into § 23.2.5.2 Line Rasterization.
"triangle-list"or"triangle-strip"-
The polygon produced in § 23.2.4 Primitive Clipping goes into § 23.2.5.4 Polygon Rasterization.
-
Remove all the points rp from rasterizationPoints that have rp.destination.position outside of state.
[[scissorRect]]. -
Return rasterizationPoints.
23.2.5.1. Point Rasterization
A single FragmentDestination is selected within the pixel containing the framebuffer coordinates of the point.
The coverage mask depends on multi-sampling mode:
- sample-frequency
-
coverageMask = 1 ≪
sampleIndex - pixel-frequency multi-sampling
-
coverageMask = 1 ≪ descriptor.
multisample.count− 1 - no multi-sampling
-
coverageMask = 1
23.2.5.2. Line Rasterization
The exact algorithm used for line rasterization is not defined, and may differ between implementations. For example, the line may be drawn using § 23.2.5.4 Polygon Rasterization of a 1px-width rectangle around the line segment, or using Bresenham’s line algorithm to select the FragmentDestinations.
Note: See Basic Line Segment Rasterization and Bresenham Line Segment Rasterization in the Vulkan 1.3 spec for more details of how line these line rasterization algorithms may be implemented.
23.2.5.3. Barycentric coordinates
Barycentric coordinates is a list of n numbers bi, defined for a point p inside a convex polygon with n vertices vi in framebuffer space. Each bi is in range 0 to 1, inclusive, and represents the proximity to vertex vi. Their sum is always constant:
∑ (bi) = 1
These coordinates uniquely specify any point p within the polygon (or on its boundary) as:
p = ∑ (bi × pi)
For a polygon with 3 vertices - a triangle, barycentric coordinates of any point p can be computed as follows:
Apolygon = A(v1, v2, v3) b1 = A(p, b2, b3) ÷ Apolygon b2 = A(b1, p, b3) ÷ Apolygon b3 = A(b1, b2, p) ÷ Apolygon
Where A(list of points) is the area of the polygon with the given set of vertices.
For polygons with more than 3 vertices, the exact algorithm is implementation-dependent. One of the possible implementations is to triangulate the polygon and compute the barycentrics of a point based on the triangle it falls into.
23.2.5.4. Polygon Rasterization
A polygon is front-facing if it’s oriented towards the projection. Otherwise, the polygon is back-facing.
Arguments:
Returns: list of RasterizationPoint.
-
Let rasterizationPoints be an empty list.
-
Let v(i) be the framebuffer coordinates for the clipped vertex number i (starting with 1) in a rasterized polygon of n vertices.
Note: this section uses the term "polygon" instead of a "triangle", since § 23.2.4 Primitive Clipping stage may have introduced additional vertices. This is non-observable by the application.
-
Determine if the polygon is front-facing, which depends on the sign of the area occupied by the polygon in framebuffer coordinates:
area = 0.5 × ((v1.x × vn.y − vn.x × v1.y) + ∑ (vi+1.x × vi.y − vi.x × vi+1.y))
The sign of area is interpreted based on the
primitive.frontFace:"ccw"-
area > 0 is considered front-facing, otherwise back-facing
"cw"-
area < 0 is considered front-facing, otherwise back-facing
-
Cull based on
primitive.cullMode:"none"-
All polygons pass this test.
"front"-
The front-facing polygons are discarded, and do not process in later stages of the render pipeline.
"back"-
The back-facing polygons are discarded.
-
Determine a set of fragments inside the polygon in framebuffer space - these are locations scheduled for the per-fragment operations. This operation is known as "point sampling". The logic is based on descriptor.
multisample:- disabled
-
Fragments are associated with pixel centers. That is, all the points with coordinates C, where fract(C) = vector2(0.5, 0.5) in the framebuffer space, enclosed into the polygon, are included. If a pixel center is on the edge of the polygon, whether or not it’s included is not defined.
Note: this becomes a subject of precision for the rasterizer.
- enabled
-
Each pixel is associated with descriptor.
multisample.countlocations, which are implementation-defined. The locations are ordered, and the list is the same for each pixel of the framebuffer. Each location corresponds to one fragment in the multisampled framebuffer.The rasterizer builds a mask of locations being hit inside each pixel and provides is as "sample-mask" built-in to the fragment shader.
-
For each produced fragment of type FragmentDestination:
-
Let rp be a new RasterizationPoint object
-
Compute the list b as § 23.2.5.3 Barycentric coordinates of that fragment. Set rp.barycentricCoordinates to b.
-
Let di be the depth value of vi.
-
Set rp.depth to ∑ (bi × di)
-
Append rp to rasterizationPoints.
-
-
Return rasterizationPoints.
23.2.6. Fragment Processing
The fragment processing stage is a programmable stage of the render pipeline that computes the fragment data (often a color) to be written into render targets.
This stage produces a Fragment for each RasterizationPoint:
-
destination refers to FragmentDestination.
-
frontFacing is true if it’s a fragment on the front face of a primitive.
-
coverageMask refers to multisample coverage mask (see § 23.2.11 Sample Masking).
-
depth refers to the depth in viewport coordinates, i.e. between the
[[viewport]]minDepthandmaxDepth. -
colors refers to the list of color values, one for each target in
colorAttachments. -
depthPassed is
trueif the fragment passed thedepthCompareoperation. -
stencilPassed is
trueif the fragment passed the stencilcompareoperation.
Arguments:
-
rp: The RasterizationPoint, produced by § 23.2.5 Rasterization.
-
descriptor: The descriptor of type
GPURenderPipelineDescriptor. -
state: The active RenderState.
Returns: Fragment or
null.
-
Let fragmentDesc be descriptor.
fragment. -
Let depthStencilDesc be descriptor.
depthStencil. -
Let fragment be a new Fragment object.
-
Set fragment.destination to rp.destination.
-
Set fragment.frontFacing to rp.frontFacing.
-
Set fragment.coverageMask to rp.coverageMask.
-
If
frag_depthbuiltin is not produced by the shader:-
Set fragment.depthPassed to the result of compare fragment(fragment.destination, fragment.depth, "depth", state.
[[depthStencilAttachment]], depthStencilDesc?.depthCompare).
-
-
Set stencilState to depthStencilDesc?.
stencilFrontif rp.frontFacing istrueand depthStencilDesc?.stencilBackotherwise. -
Set fragment.stencilPassed to the result of compare fragment(fragment.destination, state.
[[stencilReference]], "stencil", state.[[depthStencilAttachment]], stencilState?.compare). -
If fragmentDesc is not
null:-
If fragment.depthPassed is
false, thefrag_depthbuiltin is not produced by the shader entry point, and the shader entry point does not write to any storage bindings, the following steps may be skipped. -
Set the shader input builtins. For each non-composite argument of the entry point, annotated as a builtin, set its value based on the annotation:
position-
vec4<f32>(rp.destination.position, rp.depth, rp.perspectiveDivisor) front_facing-
rp.frontFacing
sample_indexsample_mask-
rp.coverageMask
-
For each user-specified shader stage input of the fragment stage:
-
Let value be the interpolated fragment input, based on rp.barycentricCoordinates, rp.primitiveVertices, and the interpolation qualifier on the input.
-
Set the corresponding fragment shader location input to value.
-
-
Invoke the fragment shader entry point described by fragmentDesc.
The device may become lost if shader execution does not end in a reasonable amount of time, as determined by the user agent.
-
If the fragment issued
discard, returnnull. -
Set fragment.colors to the user-specified shader stage output values from the shader.
-
Take the shader output builtins:
-
If
frag_depthbuiltin is produced by the shader as value:-
Let vp be state.
[[viewport]]. -
Set fragment.depth to clamp(value, vp.
minDepth, vp.maxDepth). -
Set fragment.depthPassed to the result of compare fragment(fragment.destination, fragment.depth, "depth", state.
[[depthStencilAttachment]], depthStencilDesc?.depthCompare).
-
-
-
If
sample_maskbuiltin is produced by the shader as value:-
Set fragment.coverageMask to fragment.coverageMask ∧ value.
-
Otherwise we are in § 23.2.8 No Color Output mode, and fragment.colors is empty.
-
-
Return fragment.
Arguments:
-
destination: The FragmentDestination.
-
value: The value to be compared.
-
aspect: The aspect of attachment to sample values from.
-
attachment: The attachment to be compared against.
-
compareFunc: The
GPUCompareFunctionto use, orundefined.
Returns: true if the comparison passes, or false otherwise
-
If attachment is
undefinedor does not have aspect, returntrue. -
If compareFunc is
undefinedor"always", returntrue. -
Let attachmentValue be the value of aspect of attachment at destination.
-
Return
trueif comparing value with attachmentValue using compareFunc succeeds, andfalseotherwise.
Processing of fragments happens in parallel, while any side effects,
such as writes into GPUBufferBindingType
"storage"
bindings,
may happen in any order.
23.2.7. Output Merging
Output merging is a fixed-function stage of the render pipeline that outputs the fragment color, depth and stencil data to be written into the render pass attachments.
Arguments:
-
fragment: The Fragment, produced by § 23.2.6 Fragment Processing.
-
pipeline: The current
GPURenderPipeline. -
state: The active RenderState.
-
Let depthStencilDesc be pipeline.
[[descriptor]].depthStencil. -
If pipeline.
[[writesDepth]]istrueand fragment.depthPassed istrue:-
Set the value of the depth aspect of state.
[[depthStencilAttachment]]at fragment.destination to fragment.depth.
-
-
If pipeline.
[[writesStencil]]is true:-
Set stencilState to depthStencilDesc.
stencilFrontif fragment.frontFacing istrueand depthStencilDesc.stencilBackotherwise. -
If fragment.stencilPassed is
false:-
Let stencilOp be stencilState.
failOp.
Else if fragment.depthPassed is
false:-
Let stencilOp be stencilState.
depthFailOp.
Else:
-
Let stencilOp be stencilState.
passOp.
-
-
Update the value of the stencil aspect of state.
[[depthStencilAttachment]]at fragment.destination by performing the operation described by stencilOp.
-
The depth input to this stage, if any, is clamped to the current [[viewport]]
depth
range (regardless of whether the fragment shader stage writes the frag_depth builtin).
Arguments:
-
fragment: The Fragment, produced by § 23.2.6 Fragment Processing.
-
pipeline: The current
GPURenderPipeline. -
state: The active RenderState.
-
If fragment.depthPassed is
falseor fragment.stencilPassed isfalse, return. -
Let targets be pipeline.
[[descriptor]].fragment.targets. -
For each attachment of state.
[[colorAttachments]]:-
Let color be the value from fragment.colors that corresponds with attachment.
-
Let targetDesc be the targets entry that corresponds with attachment.
-
If targetDesc.
blendis provided:-
Set the RGB components of color to the value computed by performing the operation described by colorBlend.
operationwith the values described by colorBlend.srcFactorand colorBlend.dstFactor. -
Set the alpha component of color to the value computed by performing the operation described by alphaBlend.
operationwith the values described by alphaBlend.srcFactorand alphaBlend.dstFactor.
-
Set the value of attachment at fragment.destination to color.
-
23.2.8. No Color Output
In no-color-output mode, pipeline does not produce any color attachment outputs.
The pipeline still performs rasterization and produces depth values based on the vertex position output. The depth testing and stencil operations can still be used.
23.2.9. Alpha to Coverage
In alpha-to-coverage mode, an additional alpha-to-coverage mask
of MSAA samples is generated based on the alpha component of the
fragment shader output value at @location(0).
The algorithm of producing the extra mask is platform-dependent and can vary for different pixels. It guarantees that:
-
if alpha ≤ 0.0, the result is 0x0
-
if alpha ≥ 1.0, the result is 0xFFFFFFFF
-
intermediate alpha values should result in a proportionate number of bits set to 1 in the mask. Some platforms may not guarantee that the number of bits set to 1 in the mask monotonically increases as alpha increases for a given pixel.
23.2.10. Per-Sample Shading
When rendering into multisampled render attachments, fragment shaders can be run once per-pixel or once
per-sample.
Fragment shaders must run once per-sample if either the sample_index builtin or sample interpolation sampling
is used and contributes to the shader output. Otherwise fragment shaders may run once
per-pixel with the result
broadcast out to each of the samples included in the final sample mask.
When using per-sample shading, the color output for sample N is produced by the fragment shader
execution
with sample_index == N for the current pixel.
23.2.11. Sample Masking
The final sample mask
for a pixel is computed as:
rasterization mask
& mask
& shader-output
mask.
Only the lower count
bits of the mask are considered.
If the least-significant bit at position N of the final sample mask has value of "0", the sample color outputs (corresponding to sample N) to all attachments of the fragment shader are discarded. Also, no depth test or stencil operations are executed on the relevant samples of the depth-stencil attachment.
The rasterization mask is produced by the rasterization stage, based on the shape of the rasterized polygon. The samples included in the shape get the relevant bits 1 in the mask.
The shader-output
mask takes the output value of "sample_mask" builtin
in the fragment shader.
If the builtin is not output from the fragment shader, and alphaToCoverageEnabled
is enabled, the shader-output mask becomes the alpha-to-coverage mask.
Otherwise, it defaults to 0xFFFFFFFF.
24. Type Definitions
typedef [EnforceRange ]unsigned long ;GPUBufferDynamicOffset typedef [EnforceRange ]unsigned long ;GPUStencilValue typedef [EnforceRange ]unsigned long ;GPUSampleMask typedef [EnforceRange ]long ;GPUDepthBias typedef [EnforceRange ]unsigned long long ;GPUSize64 typedef [EnforceRange ]unsigned long ;GPUIntegerCoordinate typedef [EnforceRange ]unsigned long ;GPUIndex32 typedef [EnforceRange ]unsigned long ;GPUSize32 typedef [EnforceRange ]long ;GPUSignedOffset32 typedef unsigned long long ;GPUSize64Out typedef unsigned long ;GPUIntegerCoordinateOut typedef unsigned long ;GPUSize32Out typedef unsigned long ;GPUFlagsConstant
24.1. Colors & Vectors
dictionary {GPUColorDict required double r ;required double g ;required double b ;required double a ; };typedef (sequence <double >or GPUColorDict );GPUColor
Note: double is large enough to precisely
hold 32-bit signed/unsigned
integers and single-precision floats.
r, of type double-
The red channel value.
g, of type double-
The green channel value.
b, of type double-
The blue channel value.
a, of type double-
The alpha channel value.
GPUColor
value color, depending on its type, the syntax:
-
color.r refers to either
GPUColorDict.ror the first item of the sequence (asserting there is such an item). -
color.g refers to either
GPUColorDict.gor the second item of the sequence (asserting there is such an item). -
color.b refers to either
GPUColorDict.bor the third item of the sequence (asserting there is such an item). -
color.a refers to either
GPUColorDict.aor the fourth item of the sequence (asserting there is such an item).
Arguments:
-
color: The
GPUColorto validate.
Returns: undefined
Content timeline steps:
dictionary {GPUOrigin2DDict GPUIntegerCoordinate = 0;x GPUIntegerCoordinate = 0; };y typedef (sequence <GPUIntegerCoordinate >or GPUOrigin2DDict );GPUOrigin2D
GPUOrigin2D
value origin, depending on its type, the syntax:
-
origin.x refers to either
GPUOrigin2DDict.xor the first item of the sequence (0 if not present). -
origin.y refers to either
GPUOrigin2DDict.yor the second item of the sequence (0 if not present).
Arguments:
-
origin: The
GPUOrigin2Dto validate.
Returns: undefined
Content timeline steps:
dictionary {GPUOrigin3DDict GPUIntegerCoordinate = 0;x GPUIntegerCoordinate = 0;y GPUIntegerCoordinate = 0; };z typedef (sequence <GPUIntegerCoordinate >or GPUOrigin3DDict );GPUOrigin3D
GPUOrigin3D
value origin, depending on its type, the syntax:
-
origin.x refers to either
GPUOrigin3DDict.xor the first item of the sequence (0 if not present). -
origin.y refers to either
GPUOrigin3DDict.yor the second item of the sequence (0 if not present). -
origin.z refers to either
GPUOrigin3DDict.zor the third item of the sequence (0 if not present).
Arguments:
-
origin: The
GPUOrigin3Dto validate.
Returns: undefined
Content timeline steps:
dictionary {GPUExtent3DDict required GPUIntegerCoordinate width ;GPUIntegerCoordinate height = 1;GPUIntegerCoordinate depthOrArrayLayers = 1; };typedef (sequence <GPUIntegerCoordinate >or GPUExtent3DDict );GPUExtent3D
width, of type GPUIntegerCoordinate-
The width of the extent.
height, of type GPUIntegerCoordinate, defaulting to1-
The height of the extent.
depthOrArrayLayers, of type GPUIntegerCoordinate, defaulting to1-
The depth of the extent or the number of array layers it contains. If used with a
GPUTexturewith aGPUTextureDimensionof"3d"defines the depth of the texture. If used with aGPUTexturewith aGPUTextureDimensionof"2d"defines the number of array layers in the texture.
GPUExtent3D
value extent, depending on its type, the syntax:
-
extent.width refers to either
GPUExtent3DDict.widthor the first item of the sequence (asserting there is such an item). -
extent.height refers to either
GPUExtent3DDict.heightor the second item of the sequence (1 if not present). -
extent.depthOrArrayLayers refers to either
GPUExtent3DDict.depthOrArrayLayersor the third item of the sequence (1 if not present).
Arguments:
-
extent: The
GPUExtent3Dto validate.
Returns: undefined
Content timeline steps:
-
Throw a
TypeErrorif:
25. Feature Index
25.1. "core-features-and-limits"
Allows all Core WebGPU features and limits to be used.
Note: This is currently available on all adapters and enabled automatically on all devices even if not requested.
25.2. "depth-clip-control"
Allows depth clipping to be disabled.
This feature adds the following optional API surfaces:
-
New
GPUPrimitiveStatedictionary members:
25.3. "depth32float-stencil8"
Allows for explicit creation of textures of format "depth32float-stencil8".
This feature adds the following optional API surfaces:
-
New
GPUTextureFormatenum values:
25.4. "texture-compression-bc"
Allows for explicit creation of textures of BC compressed formats which include the "S3TC", "RGTC", and "BPTC" formats. Only supports 2D textures.
Note: Adapters which support "texture-compression-bc"
do not
always support "texture-compression-bc-sliced-3d".
To use "texture-compression-bc-sliced-3d",
"texture-compression-bc"
must be enabled explicitly as this feature
does not enable the BC formats.
This feature adds the following optional API surfaces:
-
New
GPUTextureFormatenum values:
25.5. "texture-compression-bc-sliced-3d"
Allows the 3d
dimension for textures with BC compressed formats.
Note: Adapters which support "texture-compression-bc"
do not
always support "texture-compression-bc-sliced-3d".
To use "texture-compression-bc-sliced-3d",
"texture-compression-bc"
must be enabled explicitly as this feature
does not enable the BC formats.
This feature adds no optional API surfaces.
25.6. "texture-compression-etc2"
Allows for explicit creation of textures of ETC2 compressed formats. Only supports 2D textures.
This feature adds the following optional API surfaces:
-
New
GPUTextureFormatenum values:
25.7. "texture-compression-astc"
Allows for explicit creation of textures of ASTC compressed formats. Only supports 2D textures.
This feature adds the following optional API surfaces:
-
New
GPUTextureFormatenum values:
25.8. "texture-compression-astc-sliced-3d"
Allows the 3d
dimension for textures with ASTC compressed formats.
Note: Adapters which support "texture-compression-astc"
do not
always support "texture-compression-astc-sliced-3d".
To use "texture-compression-astc-sliced-3d",
"texture-compression-astc"
must be enabled explicitly as this feature
does not enable the ASTC formats.
This feature adds no optional API surfaces.
25.9. "timestamp-query"
Adds the ability to query timestamps from GPU command buffers. See § 20.4 Timestamp Query.
This feature adds the following optional API surfaces:
-
New
GPUQueryTypevalues: -
New
GPUComputePassDescriptormembers: -
New
GPURenderPassDescriptormembers:
25.10. "indirect-first-instance"
Allows the use of non-zero firstInstance values in indirect draw parameters and
indirect drawIndexed parameters.
This feature adds no optional API surfaces.
25.11.
"shader-f16"
Allows the use of the half-precision floating-point type f16 in WGSL.
This feature adds the following optional API surfaces:
-
New WGSL extensions:
25.12. "rg11b10ufloat-renderable"
Allows the RENDER_ATTACHMENT
usage on textures with format "rg11b10ufloat",
and also allows textures of that format to be blended, multisampled, and resolved.
This feature adds no optional API surfaces.
Enabling "texture-formats-tier1"
at device creation will also enable
"rg11b10ufloat-renderable".
25.13. "bgra8unorm-storage"
Allows the STORAGE_BINDING
usage on textures with format "bgra8unorm".
This feature adds no optional API surfaces.
25.14. "float32-filterable"
Makes textures with formats "r32float",
"rg32float",
and
"rgba32float"
filterable.
25.15. "float32-blendable"
Makes textures with formats "r32float",
"rg32float",
and
"rgba32float"
blendable.
25.16. "clip-distances"
Allows the use of clip_distances in WGSL.
This feature adds the following optional API surfaces:
-
New WGSL extensions:
25.17. "dual-source-blending"
Allows the use of blend_src in WGSL and simultaneously using both pixel shader
outputs
(@blend_src(0) and @blend_src(1)) as inputs to a blending operation with the
single color
attachment at location 0.
This feature adds the following optional API surfaces:
-
Allows the use of the below
GPUBlendFactors: -
New WGSL extensions:
25.18.
"subgroups"
Allows the use of the subgroup and quad operations in WGSL.
This feature adds no optional API surfaces, but the following entries of GPUAdapterInfo
expose real values whenever the feature is available on the adapter:
-
New WGSL extensions:
25.19. "texture-formats-tier1"
Supports the below new GPUTextureFormats
with the RENDER_ATTACHMENT,
blendable, multisampling
capabilities and the STORAGE_BINDING
capability
with the "read-only"
and "write-only"
GPUStorageTextureAccesses:
Allows the RENDER_ATTACHMENT,
blendable, multisampling
and resolve
capabilities on below GPUTextureFormats:
Allows the "read-only"
or "write-only"
GPUStorageTextureAccess
on below GPUTextureFormats:
Enabling "texture-formats-tier2"
at device creation will also enable
"texture-formats-tier1".
Enabling "texture-formats-tier1"
at device creation will also enable
"rg11b10ufloat-renderable".
25.20. "texture-formats-tier2"
Allows the "read-write"
GPUStorageTextureAccess
on below
GPUTextureFormats:
Enabling "texture-formats-tier2"
at device creation will also enable
"texture-formats-tier1".
25.21. "primitive-index"
Allows the use of primitive_index in WGSL.
This feature adds the following optional API surfaces:
-
New WGSL extensions:
26. Appendices
26.1. Texture Format Capabilities
26.1.1. Plain color formats
All supported plain color
formats support usages
COPY_SRC,
COPY_DST,
and
TEXTURE_BINDING,
and dimension "3d".
The RENDER_ATTACHMENT
and STORAGE_BINDING
columns
specify support for GPUTextureUsage.RENDER_ATTACHMENT
and GPUTextureUsage.STORAGE_BINDING
usage respectively.
The render
target pixel byte cost
and render
target component alignment
are used to validate the maxColorAttachmentBytesPerSample
limit.
Note: The texel block memory cost of each of these formats is the same as its texel block copy footprint.
26.1.2. Depth-stencil formats
A depth-or-stencil format is any format with depth and/or stencil aspects. A combined depth-stencil format is a depth-or-stencil format that has both depth and stencil aspects.
All depth-or-stencil formats support the COPY_SRC,
COPY_DST,
TEXTURE_BINDING,
and RENDER_ATTACHMENT
usages.
All of these formats support multisampling.
However, certain copy operations also restrict the source and destination formats, and none of
these formats support textures with "3d"
dimension.
Depth textures cannot be used with "filtering"
samplers, but can always
be used with "comparison"
samplers even if they use filtering.
| Format |
NOTE:
Texel block memory cost (Bytes)
| Aspect | GPUTextureSampleType
| Valid texel copy source | Valid texel copy destination | Texel block copy footprint (Bytes) | Aspect-specific format |
|---|---|---|---|---|---|---|---|
stencil8
| 1 − 4 | stencil | "uint"
| ✓ | 1 | stencil8
| |
depth16unorm
| 2 | depth | "depth",
"unfilterable-float"
| ✓ | 2 | depth16unorm
| |
depth24plus
| 4 | depth | "depth",
"unfilterable-float"
| ✗ | – | depth24plus
| |
depth24plus-stencil8
| 4 − 8 | depth | "depth",
"unfilterable-float"
| ✗ | – | depth24plus
| |
| stencil | "uint"
| ✓ | 1 | stencil8
| |||
depth32float
| 4 | depth | "depth",
"unfilterable-float"
| ✓ | ✗ | 4 | depth32float
|
depth32float-stencil8
| 5 − 8 | depth | "depth",
"unfilterable-float"
| ✓ | ✗ | 4 | depth32float
|
| stencil | "uint"
| ✓ | 1 | stencil8
| |||
24-bit depth refers to a 24-bit unsigned normalized depth format with a range from 0.0 to 1.0, which would be spelled "depth24unorm" if exposed.
26.1.2.1. Reading and Sampling Depth/Stencil Textures
It is possible to bind a depth-aspect GPUTextureView
to either a texture_depth_* binding or a binding with other non-depth 2d/cube texture types.
A stencil-aspect GPUTextureView
must be bound to a normal texture binding type.
The sampleType
in the GPUBindGroupLayout
must be "uint".
Reading or sampling the depth or stencil aspect of a texture behaves as if the texture contains
the values (V, X, X, X), where V is the actual depth or stencil value,
and each X is an implementation-defined unspecified value.
For depth-aspect bindings, the unspecified values are not visible through bindings with
texture_depth_* types.
tex with type texture_2d<f32>:
-
textureSample(tex, ...)will returnvec4<f32>(D, X, X, X). -
textureGather(0, tex, ...)will returnvec4<f32>(D1, D2, D3, D4). -
textureGather(2, tex, ...)will returnvec4<f32>(X1, X2, X3, X4)(a completely unspecified value).
Note:
Short of adding a new more constrained stencil sampler type (like depth), it’s infeasible for
implementations to efficiently paper over the driver differences for depth/stencil reads.
As this was not a portability pain point for WebGL, it’s not expected to be problematic in WebGPU.
In practice, expect either (V, V, V, V) or (V, 0, 0, 1) (where V is
the depth or stencil
value), depending on hardware.
26.1.2.2. Copying Depth/Stencil Textures
The depth aspects of depth32float formats
("depth32float"
and "depth32float-stencil8"
have a limited range.
As a result, copies into such textures are only valid from other textures of the same format.
The depth aspects of depth24plus formats
("depth24plus"
and "depth24plus-stencil8")
have opaque representations (implemented as either 24-bit depth or "depth32float").
As a result, depth-aspect texel
copies are not allowed with these formats.
-
All of these formats can be written in a render pass using a fragment shader that outputs depth values via the
frag_depthoutput. -
Textures with "depth24plus" formats can be read as shader textures, and written to a texture (as a render pass attachment) or buffer (via a storage buffer binding in a compute shader).
26.1.3. Packed formats
All packed texture formats support COPY_SRC,
COPY_DST,
and TEXTURE_BINDING
usages.
All of these formats are filterable.
None of these formats are renderable
or support multisampling.
A compressed format is any format with a block size greater than 1×1.
Note: The texel block memory cost of each of these formats is the same as its texel block copy footprint.